package com.tomas.lps_asi;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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.lps_asi.Adapter.RankCard_Adapter;
import com.tomas.lps_asi.Adapter.TapeMaterial_Adapter;
import com.tomas.lps_asi.ListData.Item_Lists;
import com.tomas.lps_asi.ListData.Machine_Lists;
import com.tomas.lps_asi.ListData.Material_Code_List;
import com.tomas.lps_asi.ListData.Material_Lists;
import com.tomas.lps_asi.ListData.Material_Scan;
import com.tomas.lps_asi.ListData.RankCard_Lists;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.ConvertStringToCalendar;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.MyAlert;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;
import com.tomas.lps_asi.lib.common.AsyncTcpClient;
import com.tomas.lps_asi.lib.common.Scanner;
import com.tomas.lps_asi.lib.common.Utils;

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

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

import cn.pedant.SweetAlert.SweetAlertDialog;

public class TapingLabel_Activity extends Scanner implements View.OnClickListener {
    ConstraintLayout layout_alert;
    RankCard_Adapter rankCard_adapter;
    TextView txt_date, txt_user, txt_machine, txt_model_name, txt_rank, txt_lot_no, txt_sum_qty, txt_reel_qty, txt_message;
    EditText edt_label_qty;
    RecyclerView view_rank_card, view_material;
    Calendar calendar, end_calendar, start_calendar;
    Map<String, Machine_Lists>map_machine;
    Map<String, Item_Lists> map_item;
    SimpleDateFormat date_time_fm, date_fm, date_taping_fm;
    String str_date, create_user_id, machine_no, mc_product_type, delay_time, ready_dt,ics_code, rank, dt_to_server, Ready_dt,
            item_product_type,RANK_CARD, RANK_CARD_LOT, ICS_CODE1, RANK1, NAME, CUSTOMER, QTY_REEL, GEN_LOT_TAPING, dt_taping,
            Machine_Job_No, printer_ip, Last_Machine_no, Current_Machine_no;
    String  str_dt_format = "yyyy-MM-dd HH:mm:ss", end_dt, start_dt;
    int QTY_RANK_CARD, QTY_REEL_USED, BALANCE_RANK_CARD, SUM_QTY, REQUEST_REEL_QTY, LABEL_QTY, PRINT_TIMES,DIGIT;
    boolean scan_rank_card, scan_machine, b_print, error_print, new_rank_card, change_model;
    Button btn_print;

    Map<String, RankCard_Lists> map_rank_card;
    Map<String, Material_Scan>map_material_scan;
    Map<String, Material_Code_List>map_material_list;
    List<Material_Scan>list_material_scam;
    List<RankCard_Lists> list_rank_card;
    TapeMaterial_Adapter material_adapter;
    private volatile boolean stopThread = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabping_label);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        calendar = Calendar.getInstance();
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date_fm = new SimpleDateFormat("yyyy-MM-dd");
        date_taping_fm = new SimpleDateFormat("yyyyMMdd");
//        str_date = date_fm.format(calendar.getTime());

        scan_rank_card = false;
        scan_machine = false;
        b_print = false;
        error_print = false;
        stopThread = true;
        new_rank_card = false;
        change_model = false;

        map_machine = new LinkedHashMap<>();
        map_rank_card = new LinkedHashMap<>();
        map_item = new LinkedHashMap<>();
        map_material_scan = new LinkedHashMap<>();
        map_material_list = new LinkedHashMap<>();
        list_material_scam = new ArrayList<Material_Scan>();
        list_rank_card = new ArrayList<RankCard_Lists>();

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);

        btn_print = (Button)findViewById(R.id.btn_print);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
        btn_print.setEnabled(false);

        txt_date = (TextView) findViewById(R.id.txt_date);
//        txt_date.setText(str_date);

        txt_user = (TextView) findViewById(R.id.txt_user_id);
        txt_machine = (TextView) findViewById(R.id.txt_machine_code);
        txt_model_name = (TextView) findViewById(R.id.txt_model_name);
        txt_rank = (TextView) findViewById(R.id.txt_rank);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_sum_qty = (TextView) findViewById(R.id.txt_sum_qty);
        txt_reel_qty = (TextView) findViewById(R.id.txt_reel_qty);
        txt_message = (TextView)findViewById(R.id.txt_message);

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

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

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

    }

    @Override
    protected void onStart() {
        super.onStart();

        Check_Time();

    }

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

            case R.id.btn_clear:
                //clear list rank card
                if (error_print == false) {
                    map_rank_card.clear();
                    Set_View_RankCard();
                    Clear_Layout();
                }
                break;

            case R.id.btn_print:
                //print
                if (b_print == false){
                    if (error_print == true){//print error --> print again
                        Command_Print();

                    }else {
                        Block_button();
                        Check_DataInput();
                    }
                }
                break;
        }
    }

    private void Check_Time() {
        calendar = Calendar.getInstance();
        try {
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
            String current_time = sdf.format(today);
            Date start = sdf.parse("08:00 AM");
            Date current = sdf.parse(current_time);

            if (current.before(start)) {
                calendar.add(Calendar.DATE, -1);
            }
            str_date = date_fm.format(calendar.getTime());
            txt_date.setText(str_date);

        } catch (ParseException e) {
            // Invalid date was entered
        }
    }

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

        if (error_print == true)
            return;

        try {
            String scan = data.trim();
            Log.d(getString(R.string.tag), "scan data : " + scan);
            Log.d(getString(R.string.tag), "ics_code : " + ics_code);
            Log.d(getString(R.string.tag), "scan_rank_card : " + scan_rank_card);

            if (scan_rank_card == true){//scan lot no. of rank card
                if (scan.substring(0,1).trim().equals("E")){
                    RANK_CARD_LOT = scan;

                    //23042025
                    Check_RC_MC(RANK_CARD, RANK_CARD_LOT, item_product_type);

                }else{
                    new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR Code ไม่ถูกต้อง!")
                            .show();
                }
            }else {
                if (scan.length() == 6) {//scan user
                    if (Settings.getMap_user().containsKey(scan)){
                        if (Settings.getMap_user().get(data.trim()).getTaping().trim().equals("1")){
                            create_user_id = scan;
                            txt_user.setText(create_user_id);

                        }else {
                            txt_user.setText("");
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่อนุญาตให้ทำ Taping")
                                    .show();
                        }
                    }else {
                        txt_user.setText("");
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบรหัสพนักงาน!")
                                .show();
                    }
                } else if (scan.substring(0,2).trim().equals("TP") ) {//scan machine
                    Check_Machine(scan);

                }else if (scan.substring(0,2).trim().equals("CV")||scan.substring(0,2).trim().equals("CR")) {
                    if (ics_code.trim().equals("")){
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกน rank card!")
                                .show();
                        return;
                    }

                    if (map_material_scan.containsKey(scan)) {
                        map_material_scan.remove(scan);
                        Set_View_Material_Scan();
                    } else {
                        Check_Material_dt(scan);
                    }

                }else {//scan rank card or another.
                    if (txt_machine.getText().toString().trim().equals("")){//check scan machine
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกนเครื่องจักร!")
                                .show();
                    }else{
                        int sum_qty, qty_reel;
                        String sum = txt_sum_qty.getText().toString().trim();
                        sum_qty = Integer.parseInt(sum);
                        String reel = txt_reel_qty.getText().toString().trim();
                        qty_reel = Integer.parseInt(reel);
                        Log.d(getString(R.string.tag), "if: " + sum+"|"+reel);

                        if (sum_qty > 0 && sum_qty == qty_reel){
                            MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                            alert.setMessage("จำนวนครบแล้ว");
                            alert.show();

                        }else {
                            txt_lot_no.setText("");
                            map_rank_card.clear();//23042025
                            RANK_CARD = scan;
                            ics_code = scan.trim().substring(0, 10);
                            Check_ICS_Code(ics_code);
                        }
                    }
                }
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_RC_MC(String rank_card, String lot_no, String type) {//23042025
        //เป็นการเช็คว่า Rank Card นี้ ใช้กับเครื่องนี้อยู่ใช่หรือไม่
        //get สถานะเครื่องจักร ปัจจุบันว่า เดินงาน rankcard ไหนอยู่ ต้องเดินต่อ หรือchange model ได้
        Log.d(getString(R.string.tag), "Check_RankCard : " + rank_card+"|"+lot_no+"|"+type);
        Log.d(getString(R.string.tag), "map_machine : " + map_machine.size());

        if (map_machine.containsKey(type)) {
            Log.d(getString(R.string.tag), "map_machine.containsKey if");
            Machine_Lists mc = map_machine.get(type);
            String old_rank_card = mc.getRank_card();
            String old_lot_no = mc.getLot_no();
            String balance = mc.getBalance();
            Integer int_balance = Integer.parseInt(balance);
            Log.d(getString(R.string.tag), old_rank_card+"|"+old_lot_no+"|"+balance);

            if(!old_rank_card.trim().equals("") && !old_lot_no.trim().equals("")){
                if (int_balance == 0){
                    SweetAlertDialog d = new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE);
                    d.setCancelable(false);
                    d.setTitleText("แจ้งเตือน");
                    d.setContentText("ต้องการ Change Model ใช่หรือไม่?");
                    d.setCancelText("ไม่");
                    d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sd) {
                            sd.dismiss();
                            Clear_Layout();
                        }
                    });
                    d.setConfirmText("ใช่");
                    d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sd) {
                            sd.dismiss();
                            change_model = true;
                            Rank_Card_OK(lot_no);
                        }
                    });
                    d.show();

                }else {//balance > 0
                    if (old_rank_card.trim().equals(rank_card) && old_lot_no.trim().equals(lot_no)){
                        Rank_Card_OK(lot_no);

                    }else {
                        MyAlert alert = new MyAlert(TapingLabel_Activity.this);
                        alert.setMessage("ไม่สามารถสแกนใบนี้กับเครื่องนี้ได้ \n กรุณาสแกน Rank Card นี้ \n"+old_rank_card+"\n"+old_lot_no);
                        alert.show();
                        Clear_Layout();
                    }
                }
            }else {
                Rank_Card_OK(lot_no);
            }

        }else {
            MyAlert alert = new MyAlert(TapingLabel_Activity.this);
            alert.setMessage("Type ไม่ตรงกัน!");
            alert.show();
        }
    }

    private void Rank_Card_OK(String lot_no) {//23042025
        Log.d(getString(R.string.tag), "Rank_Card_OK : ");
        txt_lot_no.setText(lot_no);
        Check_Balance(RANK_CARD, lot_no, QTY_RANK_CARD);
        scan_rank_card = false;
        txt_model_name.setTextColor(Color.parseColor("#8A8888"));
        txt_rank.setTextColor(Color.parseColor("#8A8888"));
    }

    private void Check_Material_dt(String scan) {
        String[] tokens = scan.trim().split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
        Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
        if (tokens.length == 4){
            String M_Type = tokens[0];
            String M_Code = tokens[1];
            String M_lot_no = tokens[2];
            String M_Exp = tokens[3];
            try {
                Calendar now = Calendar.getInstance();
                Calendar now_dt = (Calendar) now.clone();
                Log.d(getString(R.string.tag), "now_dt: " + now_dt);
                String str_format_dt = "yyyy-MM-dd";

                Calendar exp_dt = ConvertStringToCalendar.convert(M_Exp, str_format_dt);
                String str_exp_dt = date_fm.format(exp_dt.getTime());
                Log.d(getString(R.string.tag), "str_exp_dt: " + str_exp_dt);

                if (now_dt.before(exp_dt)){
                    //check material
                    String M_Key = M_Type+M_Code;
                    String type = null;
                    Boolean check_type = false;
                    if (map_material_list.containsKey(M_Key)){
                        if (map_material_scan.size() > 0){//check duplicate material type
                            for (String key : map_material_scan.keySet()){
                                Material_Scan data = map_material_scan.get(key);
                                type = data.getMaterial_type();

                                if (type.trim().equals(M_Type)){
                                    check_type = true;
                                }
                            }
                            if (check_type == true){
                                new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("สแกน "+M_Type+" แล้ว!")
                                        .show();
                                return;
                            }
                        }

                        map_material_scan.put(scan, new Material_Scan(
                                "",
                                M_Code,
                                map_material_list.get(M_Key).getMaterial_name().trim(),
                                M_lot_no,
                                M_Type,
                                M_Exp));
                        Set_View_Material_Scan();

                    }else {
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบ Material!")
                                .show();
                    }

                }else {
                    new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("Material หมดอายุแล้ว!")
                            .show();
                }
            } catch (Exception e) {
                new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR get_date")
                        .setContentText(e.getMessage())
                        .show();
            }

        }else {
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("QR Code ไม่ถูกต้อง!")
                    .show();
        }
    }

    private void Set_View_Material_Scan() {
        list_material_scam.clear();
        for (String key : map_material_scan.keySet()){
            Material_Scan m_data = map_material_scan.get(key);
            list_material_scam.add(new Material_Scan(
                    "",
                    m_data.getMaterial_code(),
                    m_data.getMaterial_name(),
                    m_data.getMaterial_lot_no(),
                    m_data.getMaterial_type(),
                    m_data.getMaterial_exp()));
        }
        Log.d("ASI", "for list : " + list_material_scam.size());
        material_adapter = new TapeMaterial_Adapter(list_material_scam, TapingLabel_Activity.this);
        view_material.setAdapter(material_adapter);
    }

    private void Check_ICS_Code(String ics_code) {
        map_item.clear();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("ics_code", ics_code);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ ICS Code!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                DIGIT =   jArray.getJSONObject(i).getInt("Digit");
                                String KEY = jArray.getJSONObject(i).getString("ICS_Code").trim()+jArray.getJSONObject(i).getString("Rank").trim();
                                Log.d(getString(R.string.tag), "KEY: " + KEY);
                                map_item.put(KEY,
                                        new Item_Lists(
                                                jArray.getJSONObject(i).getString("ICS_Code").trim(),
                                                jArray.getJSONObject(i).getString("Product_Name").trim(),
                                                jArray.getJSONObject(i).getString("Rank").trim(),
                                                jArray.getJSONObject(i).getString("Digit").trim(),
                                                jArray.getJSONObject(i).getString("Customer_Reference").trim(),
                                                jArray.getJSONObject(i).getString("Qty_Reel").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim()));

                            }
                            layout_alert.setVisibility(View.GONE);
                            try {
                                //subString RankCard
                                Log.d(getString(R.string.tag), "RANK_CARD: " + RANK_CARD);
                                rank = RANK_CARD.substring(10, 10 + DIGIT);
                                Log.d(getString(R.string.tag), "RANK: " + rank);
                                String qty = RANK_CARD.substring(10 + DIGIT);
                                QTY_RANK_CARD = Integer.parseInt(qty);
                                Log.d(getString(R.string.tag), "qty: " + qty + " / " + String.valueOf(QTY_RANK_CARD));

                                    String key = ics_code + rank;
                                    Log.d(getString(R.string.tag), "key: " + key);

                                    if (map_item.containsKey(key)) {//get data ics_code+rank
                                        Item_Lists item = map_item.get(key);
                                        NAME = item.getProduct_Name();
                                        CUSTOMER = item.getCustomer_Reference();
                                        QTY_REEL = item.getQty_Reel();
                                        item_product_type = item.getType();
                                        Log.d(getString(R.string.tag), "Item: " + NAME + "|" + CUSTOMER + "|" + QTY_REEL + "|" + item_product_type);

                                        //check type
                                        if (map_machine.containsKey(item_product_type)) {
                                            Machine_Lists mc = map_machine.get(item_product_type);
                                            machine_no = mc.getMachine_No();
                                            mc_product_type = mc.getType();
                                            delay_time = mc.getDelay_min();
                                            printer_ip = mc.getPrinter_IP();
                                            ready_dt = mc.getReady_dt();

                                            Check_MC_Ready(ready_dt, mc.getMachine_Code());

                                        } else {
                                            MyAlert alert = new MyAlert(TapingLabel_Activity.this);
                                            alert.setMessage("Type ไม่ตรงกัน!");
                                            alert.show();

                                        }
                                    } else {
                                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("ไม่พบ Rank : " + rank)
                                                .show();
                                    }
                            }catch (Exception e){
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("sub string rank card error!")
                                        .show();
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }



    private void Check_DataInput() {
        int sum_qty, qty_reel;
        String sum = txt_sum_qty.getText().toString().trim();
        sum_qty = Integer.parseInt(sum);
        String reel = txt_reel_qty.getText().toString().trim();
        qty_reel = Integer.parseInt(reel);
        Log.d(getString(R.string.tag), "if: " + sum+"|"+reel);


        if (edt_label_qty.getText().toString().equals("")||edt_label_qty.getText().toString().equals("0")){
            edt_label_qty.setText("2");
        }

        if (map_rank_card.size() == 0){
            Unblock_button();
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกน Rank Card!")
                    .show();
        }else{
            if (sum_qty == qty_reel){
                if (txt_user.getText().toString().trim().equals("")){
                    Unblock_button();
                    new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกนรหัสพนักงาน!")
                            .show();
                }else{
                    //check_material
                    Boolean CR = false, CV = false;
                    for (String K : map_material_scan.keySet()){
                        Material_Scan data = map_material_scan.get(K);
                        String type = data.getMaterial_type();

                        if (type.trim().equals("CR")){
                            CR = true;
                        }else if (type.trim().equals("CV")){//CV
                            CV = true;
                        }
                    }

                    if (CV == true && CR == true) {
                        Generate_Label();

                    }else {
                        Unblock_button();
                        MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                        alert.setMessage("ยังสแกน material ไม่ครบ!");
                        alert.show();
                    }
                }
            } else {
                Unblock_button();
                MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                alert.setMessage("จำนวนยังไม่ครบ!");
                alert.show();
            }
        }
    }


    private void Block_button() {
        b_print = true;
        btn_print.setEnabled(false);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_print = false;
        btn_print.setEnabled(true);
        btn_print.setBackgroundResource(R.drawable.button_backgroup_green);
    }

    private void Generate_Label() {
        //get start_dt end_dt
        start_calendar = Calendar.getInstance();
        end_calendar = Calendar.getInstance();
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        try {//check date time before 8:00AM
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
            String current_time = sdf.format(today);
            Date start = sdf.parse("08:00 AM");
            Date current = sdf.parse(current_time);

            if (current.before(start)) {
                Log.d("get_start_dt", "before" );

                start_calendar.add(Calendar.DATE, -1);
                start_dt = date_fm.format(start_calendar.getTime());

                calendar.add(Calendar.DATE, -1);
                dt_taping = date_taping_fm.format(calendar.getTime());

                end_dt = date_fm.format(end_calendar.getTime());

            }else{
                Log.d("get_start_dt", "after" );
                end_calendar.add(Calendar.DATE, +1);
                end_dt = date_fm.format(end_calendar.getTime());

                start_dt = date_fm.format(start_calendar.getTime());
                dt_taping = date_taping_fm.format(calendar.getTime());

            }
        } catch (ParseException e) {
            // Invalid date was entered
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR get_date")
                    .setContentText(e.getMessage())
                    .show();
        }

        start_dt = start_dt + " 08:00:00";
        end_dt = end_dt + " 07:59:59";

        Log.d(getString(R.string.tag), "start_dt: " + start_dt);
        Log.d(getString(R.string.tag), "end_dt: " + end_dt);
        Log.d(getString(R.string.tag), "dt_taping: " + dt_taping);//yyyyMMdd

        String year, month, date;//date for gen lot
        year = dt_taping.substring(3,4);
        month =  dt_taping.substring(4,6);
        date = dt_taping.substring(6,8);

        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);


        calendar.add(Calendar.MINUTE, Integer.parseInt(delay_time));
        Ready_dt = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "Ready_dt : " + Ready_dt);


        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            //for insert taping_lot
            JSONArray jArray_tapping_lot = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("machine_code", txt_machine.getText().toString().trim());
            jsonParams.put("machine_no", machine_no);
            jsonParams.put("taping_lot","");
            jsonParams.put("type", mc_product_type);
            jsonParams.put("create_user_id", txt_user.getText().toString().trim());
            jsonParams.put("create_dt", dt_to_server);
            JSONObject jsonObj = new JSONObject(jsonParams);
            jArray_tapping_lot.put(jsonObj);

            //insert table TapingLabel
            JSONArray jArray_tapping_label = new JSONArray();
            Map<String, String> jsonTapingLabel = new HashMap<>();
            jsonTapingLabel.put("taping_lot_no", "");
            jsonTapingLabel.put("ics_code", ICS_CODE1);
            jsonTapingLabel.put("product_name",  txt_model_name.getText().toString().trim());
            jsonTapingLabel.put("rank",  RANK1);
            jsonTapingLabel.put("type",  mc_product_type);
            jsonTapingLabel.put("cust_ref", CUSTOMER);
            jsonTapingLabel.put("machine_no", machine_no);
            jsonTapingLabel.put("taping_qty", txt_sum_qty.getText().toString().trim());
            jsonTapingLabel.put("label_qty", edt_label_qty.getText().toString().trim());
            jsonTapingLabel.put("label_type", Settings.getLabelType());
            jsonTapingLabel.put("remark", "");
            jsonTapingLabel.put("create_dt", dt_to_server);
            jsonTapingLabel.put("create_user_id", txt_user.getText().toString().trim());
            jsonTapingLabel.put("ref_id", "");
            JSONObject jsonObjTL = new JSONObject(jsonTapingLabel);
            jArray_tapping_label.put(jsonObjTL);

            //insert table RankCard
            JSONArray jArray_RankCard = new JSONArray();
            for (String key : map_rank_card.keySet()){
                RankCard_Lists lists = map_rank_card.get(key);

                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("rank_card", lists.getRankCard());
                jsParams.put("lot_no", lists.getLotNo());
                jsParams.put("machine_no",machine_no );//23042025
                jsParams.put("type",  mc_product_type);//23042025
                jsParams.put("ics_code", ICS_CODE1);
                jsParams.put("product_name", txt_model_name.getText().toString().trim());
                jsParams.put("rank", RANK1);
                jsParams.put("qty", lists.getQty_RankCard());
                jsParams.put("qty_used", lists.getQty_Used());
                jsParams.put("balance", lists.getBalance_RankCard());
                jsParams.put("taping_lot_no", "");
                jsParams.put("create_dt", dt_to_server);
                jsParams.put("ref_id", "");
                JSONObject jsObj = new JSONObject(jsParams);
                jArray_RankCard.put(jsObj);
            }

            //insert table MaterialFactorList
            JSONArray jArray_Material = new JSONArray();
            for (String key : map_material_scan.keySet()){
                Material_Scan lists = map_material_scan.get(key);

                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("taping_lot_no", "");
                jsParams.put("material_code", lists.getMaterial_code());
                jsParams.put("material_name", lists.getMaterial_name());
                jsParams.put("material_lot_no", lists.getMaterial_lot_no());
                jsParams.put("material_type", lists.getMaterial_type());
                jsParams.put("material_exp", lists.getMaterial_exp());
                jsParams.put("create_dt", dt_to_server);
                jsParams.put("create_user_id",txt_user.getText().toString().trim() );
                JSONObject jsObj = new JSONObject(jsParams);
                jArray_Material.put(jsObj);
            }

            JSONObject json = new JSONObject();
            json.put("cmd", "generate_label");
            json.put("label_type", Settings.getLabelType());
            json.put("machine_no",machine_no );
            json.put("rank",RANK1 );
            json.put("start_dt",start_dt );
            json.put("end_dt",end_dt );
            json.put("Ready_dt",Ready_dt);
            json.put("year",year);
            json.put("month",month);
            json.put("date",date);
            json.put("tap_datas",jArray_tapping_lot);
            json.put("label_datas",jArray_tapping_label);
            json.put("rank_card_datas",jArray_RankCard);
            json.put("material_datas",jArray_Material);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/generate_label.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) {
                            GEN_LOT_TAPING = jsonObject.getString("error");
                            Log.d(getString(R.string.tag), "GEN_LOT_TAPING : " + GEN_LOT_TAPING);
                            Command_Print();

                        } else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(jsonObject.getString("error"))
                                    .show();
                        }

                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }


    private void Command_Print() {
        if (ICS_CODE1.trim().equals("")//check data
                ||txt_model_name.getText().toString().trim().equals("")
                ||txt_sum_qty.getText().toString().trim().equals("0")
                ||GEN_LOT_TAPING.trim().equals("")){

            MyAlert alert = new MyAlert(TapingLabel_Activity.this);
            alert.setMessage("การสั่งพิมพ์เกิดข้อผิดพลาด +\n+ กรุณาแจ้ง LEADER +\n+ เพื่อสั่งพิมพ์ defective label");
            alert.show();

            txt_user.setText("");
            Clear_Layout();

        }else {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("Printing label....");

            String str_qty_label = edt_label_qty.getText().toString().trim();
            LABEL_QTY = Integer.parseInt(str_qty_label);
            PRINT_TIMES = 0;
            stopThread = false;
            Log.d("Thread.sleep", "stopThread: " + stopThread+":"+PRINT_TIMES);

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


    class ExampleRunnable implements Runnable {

        @Override
        public void run() {
            while (!stopThread) {
                try {
                    Print_Label();
                    Thread.sleep(4000);
                    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);
        }

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";
            String payload = String.format(
                    "%s|%s|%s|%s|%s|%s"
                    , ICS_CODE1
                    , txt_model_name.getText().toString().trim()
                    , txt_sum_qty.getText().toString().trim()
                    , GEN_LOT_TAPING
                    , CUSTOMER
                    ,"");

            String tmp = String.format(
                    "%s %s\r\n%s%s"
                    , "PST"
                    ,printer_ip
                    , ""
                    , payload
            );

            Log.d(getString(R.string.tag), "payload: " + payload);
            new AsyncTcpClient(getApplicationContext(),
                    Settings.getMgmtList().get("printer_server_ip"),
                    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) {
                            layout_alert.setVisibility(RelativeLayout.GONE);
                            Toast.makeText(TapingLabel_Activity.this, "Print : OK", Toast.LENGTH_SHORT).show();
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("SUCCESS")
                                    .setContentText("Print : OK")
                                    .show();
                            txt_user.setText("");
                            Clear_Layout();
                        }

                    } else {
                        error_print = true;
                        layout_alert.setVisibility(RelativeLayout.GONE);
                        Unblock_button();
                        new SweetAlertDialog(TapingLabel_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 Check_Balance(String rank_card, String rank_card_lot, int qty) {
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("rank_card", rank_card);
            json.put("lot_no", rank_card_lot);

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

                    try {
                        JSONArray jArray = new JSONArray(response);

                        if (jArray.length() == 0){ // no history rank card
                            QTY_RANK_CARD = qty;
                            new_rank_card = true; // New RankCard

                        }else {
                            new_rank_card = false;// Old RankCard

                            String  balance = "";
                            for (int i = 0; i < jArray.length(); i++) {
                                balance = jArray.getJSONObject(i).getString("balance").trim();
                                Last_Machine_no = jArray.getJSONObject(i).getString("machine_no").trim();
                            }
                            QTY_RANK_CARD = Integer.parseInt(balance);
                        }
                        //23042025
                        if (QTY_RANK_CARD == 0) {
                            MyAlert alert = new MyAlert(TapingLabel_Activity.this);
                            alert.setMessage("จำนวน Rank Card = 0");
                            alert.show();
                            if (map_rank_card.size() == 0) {
                                Clear_RankCard();
                            } else {
                                txt_lot_no.setText("");
                            }
                        } else {
                            if (change_model == true || new_rank_card == true){
                                Calculate_Qty();
                            }else {
                                if (Last_Machine_no.trim().equals(Current_Machine_no)) { //เช็ค Rank card ว่า Rank card ถูกใช้อยู่ที่เครื่องไหน
                                    Calculate_Qty();
                                }else {
                                    MyAlert alert = new MyAlert(TapingLabel_Activity.this);
                                    alert.setMessage("ขณะนี้ Rank Card นี้ \nถูกใช้อยู่ที่เครื่อง "+Last_Machine_no);
                                    alert.show();
                                    Clear_Layout();
                                }
                            }
                        }
//                        if (QTY_RANK_CARD == 0){
//                            MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
//                            alert.setMessage("จำนวน Rank Card = 0");
//                            alert.show();
//                            if (map_rank_card.size() == 0){
//                                Clear_RankCard();
//                            }else {
//                                txt_lot_no.setText("");
//                            }
//                        }else{
//                            Calculate_Qty();
//                        }

                        layout_alert.setVisibility(View.GONE);
                        Log.d(getString(R.string.tag), "QTY_RANK_CARD: " + String.valueOf(QTY_RANK_CARD));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Calculate_Qty() {

        BALANCE_RANK_CARD = 0;
        String sum = txt_sum_qty.getText().toString().trim();
        int sum_qty = Integer.parseInt(sum);
        SUM_QTY = (REQUEST_REEL_QTY - sum_qty);
        Log.d(getString(R.string.tag), "QTY_TAPING: " +
                String.valueOf(SUM_QTY+"="+REQUEST_REEL_QTY+"-"+  sum_qty));

        if (SUM_QTY == 0){
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("จำนวนครบแล้ว")
                    .show();
        }else {
            if (QTY_RANK_CARD > SUM_QTY) {
                BALANCE_RANK_CARD = (QTY_RANK_CARD - SUM_QTY);
                Log.d(getString(R.string.tag), "BALANCE_RANK_CARD: " +
                        String.valueOf(BALANCE_RANK_CARD + "=" + QTY_RANK_CARD + "-" + SUM_QTY));

                QTY_REEL_USED = SUM_QTY;
                Log.d(getString(R.string.tag), "QTY_REEL_USE: " + QTY_REEL_USED);
                AddMap_RankCard();

            } else if (QTY_RANK_CARD == SUM_QTY) {
                BALANCE_RANK_CARD = 0;
                QTY_REEL_USED = SUM_QTY;
                Log.d(getString(R.string.tag), "QTY_REEL_USE: " + QTY_REEL_USED);
                AddMap_RankCard();

            } else {//QTY_RANK_CARD < int_QTY_REEL
                if (new_rank_card == true){//rank cardใหม่ ไม่เคยออก taping
                    BALANCE_RANK_CARD = 0;
                    QTY_REEL_USED = QTY_RANK_CARD;
                    Log.d(getString(R.string.tag), "QTY_REEL_USE: " + QTY_REEL_USED);
                    AddMap_RankCard();

                }else {//rank card ที่จำนวนเหลือไม่พอ taping
                    MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                    alert.setMessage("มีจำนวนไม่พอ Taping"+"\n"+"กรุณาพิมพ์ใบเศษ");

                    if (map_rank_card.size() == 0) {//
                        alert.next_activity(true);
                    }

                    alert.show();
                }
            }
        }
    }

    private void AddMap_RankCard() {
        map_rank_card.put(RANK_CARD+RANK_CARD_LOT, new RankCard_Lists(
                RANK_CARD,
                RANK_CARD_LOT,
                String.valueOf(QTY_REEL_USED) ,
                String.valueOf(QTY_RANK_CARD),
                String.valueOf(BALANCE_RANK_CARD)));
        Log.d(getString(R.string.tag), "AddMap_RankCard: " + map_rank_card.size());

        Set_View_RankCard();
    }

    private void Set_View_RankCard() {
//        txt_lot_no.setText("");
        list_rank_card.clear();

        if (map_rank_card.size() == 0){
            Clear_RankCard();

        }else {
            int sum_qty = 0, int_qty = 0;
            for (String key : map_rank_card.keySet()){
                RankCard_Lists card_lists = map_rank_card.get(key);
                list_rank_card.add(new RankCard_Lists(
                        card_lists.getRankCard(),
                        card_lists.getLotNo(),
                        card_lists.getQty_Used(),
                        card_lists.getQty_RankCard(),
                        card_lists.getBalance_RankCard()
                ));

                int_qty = Integer.parseInt(card_lists.getQty_Used());
                sum_qty = (sum_qty + int_qty);
            }
            txt_sum_qty.setText(String.valueOf(sum_qty));
        }

        rankCard_adapter = new RankCard_Adapter(list_rank_card, TapingLabel_Activity.this);
        view_rank_card.setAdapter(rankCard_adapter);
    }

    private void Clear_RankCard() {
        txt_model_name.setText("");
        txt_rank.setText("");
        txt_lot_no.setText("");
        txt_sum_qty.setText("0");
        txt_reel_qty.setText("0");
        ics_code = "";
        rank = "";
        ICS_CODE1 = "";
        RANK1 = "";
        scan_rank_card = false;
        if (map_rank_card.size() == 0){
            txt_model_name.setTextColor(Color.parseColor("#FF000000"));
            txt_rank.setTextColor(Color.parseColor("#FF000000"));
        }
    }

    private void Clear_Layout() {
//        txt_user.setText("");
        txt_machine.setText("");
        txt_model_name.setText("");
        txt_rank.setText("");
        txt_lot_no.setText("");
        txt_sum_qty.setText("0");
        txt_reel_qty.setText("0");
        edt_label_qty.setText("2");
        ics_code = "";
        rank = "";
        ICS_CODE1 = "";
        RANK1 = "";
        GEN_LOT_TAPING = "";
        Last_Machine_no = "";
        Current_Machine_no = "";
        scan_rank_card = false;
        scan_machine = false;
        b_print = false;
        error_print = false;
        stopThread = true;
        change_model = false;
        map_rank_card.clear();
        map_material_scan.clear();
        map_material_list.clear();
        list_material_scam.clear();
        txt_model_name.setTextColor(Color.parseColor("#FF000000"));
        txt_rank.setTextColor(Color.parseColor("#FF000000"));
        btn_print.setBackgroundResource(R.drawable.button_backgroup_gray);
        btn_print.setEnabled(false);
        Set_View_RankCard();
        Set_View_Material_Scan();
    }

    private void Check_Machine(String machine_code) {
        map_machine.clear();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
//            json.put("cmd", "search");23042025
            json.put("cmd", "check_mc_rc");
            json.put("machine_code", machine_code);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            txt_machine.setText("");
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                String Ready_dt_db = jArray.getJSONObject(i).getString("Ready_dt").trim()== "null" ? "" : jArray.getJSONObject(i).getString("Ready_dt").trim();
                                if (Ready_dt_db.trim().equals("")){
                                    ready_dt = "";
                                }else {
                                    JSONObject obj = jArray.getJSONObject(i);
                                    JSONObject array_ready_dt = obj.getJSONObject("Ready_dt");
                                        ready_dt = array_ready_dt.getString("date");
                                        ready_dt = ready_dt.substring(0, 19);
                                }
                                //23042025
                                Current_Machine_no = jArray.getJSONObject(i).getString("Machine_No").trim();
                                map_machine.put(jArray.getJSONObject(i).getString("Type").trim(),
                                        new Machine_Lists(
                                                Current_Machine_no,
                                                jArray.getJSONObject(i).getString("Machine_Code").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Delay_min").trim(),
                                                ready_dt,
                                                jArray.getJSONObject(i).getString("Printer_IP").trim(),
                                                jArray.getJSONObject(i).getString("rank_card").trim(),
                                                jArray.getJSONObject(i).getString("lot_no").trim(),
                                                jArray.getJSONObject(i).getString("balance").trim()));
                            }

                            Log.d(getString(R.string.tag), "ready_dt: " + ready_dt);
                            Log.d(getString(R.string.tag), "map_machine: " + map_machine.size());

                            map_rank_card.clear();
                            Set_View_RankCard();
                            txt_machine.setText(machine_code);
                            layout_alert.setVisibility(View.GONE);

                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_MC_Ready(String mc_ready_dt, String machine_code) {
        Log.d(getString(R.string.tag), "ready_dt: " + mc_ready_dt);
        Get_material();

        if(!mc_ready_dt.trim().equals("")) {
            Calendar c_ready_dt= ConvertStringToCalendar.convert(mc_ready_dt, str_dt_format);
            String str_ready_dt = date_time_fm.format(c_ready_dt.getTime());
            Log.d(getString(R.string.tag), "str_ready_dt: " + str_ready_dt.toString());

            Calendar now = Calendar.getInstance();
            Calendar now_dt = (Calendar) now.clone();
            String str_now = date_time_fm.format(now_dt.getTime());
            Log.d(getString(R.string.tag), "now_dt: " + str_now);

            if (now_dt.after(c_ready_dt)) {
                txt_machine.setText(machine_code);
                scan_machine = true;

                txt_model_name.setText(NAME);
                txt_rank.setText(rank);
                txt_reel_qty.setText(QTY_REEL);
                REQUEST_REEL_QTY = Integer.parseInt(QTY_REEL);
                scan_rank_card = true;

                if (map_rank_card.size() == 0){//Default data
                    ICS_CODE1 = ics_code;
                    RANK1 = rank;
                }

            } else {
                txt_machine.setText("");
                scan_machine = false;
                MyAlert alert =  new MyAlert(TapingLabel_Activity.this);
                alert.setMessage("เครื่องจักรกำลังทำงาน"+"\n"+"จะพร้อมใช้งานเวลา \n\n"+mc_ready_dt);
                alert.show();
            }
        }else {//first time machine working
            txt_machine.setText(machine_code);
            scan_machine = true;

            txt_model_name.setText(NAME);
            txt_rank.setText(rank);
            txt_reel_qty.setText(QTY_REEL);
            REQUEST_REEL_QTY = Integer.parseInt(QTY_REEL);
            scan_rank_card = true;

            if (map_rank_card.size() == 0){//Default data
                ICS_CODE1 = ics_code;
                RANK1 = rank;
            }

        }
        Log.d(getString(R.string.tag), "response: " + machine_no+" | "+ mc_product_type+" | "+delay_time);
        layout_alert.setVisibility(View.GONE);
    }

    private void Get_material() {
        map_material_list.clear();
        try {
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
            layout_alert.setVisibility(View.VISIBLE);

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("ics_code", ics_code);

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            Clear_Layout();
                            new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ material! \n กรุณาแจ้ง Leader")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {

                                map_material_list.put(jArray.getJSONObject(i).getString("material_type").trim()+jArray.getJSONObject(i).getString("material_code").trim(),
                                        new Material_Code_List(
                                                jArray.getJSONObject(i).getString("material_code").trim(),
                                                jArray.getJSONObject(i).getString("material_name").trim(),
                                                jArray.getJSONObject(i).getString("material_type").trim()));
                            }

                            Log.d(getString(R.string.tag), "map_material_list: " + map_material_list.size());

                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(TapingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(TapingLabel_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 P2:
                    if (b_print == false){
                        if (error_print == true){//print error --> print again
                            Command_Print();

                        }else {
                            Block_button();
                            Check_DataInput();
                        }
                    }
                    break;

                case P3:
                    if (error_print == false) {
                        map_rank_card.clear();
                        Set_View_RankCard();
                        Clear_Layout();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}