package com.tomas.pcs_asi;

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.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
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.pcs_asi.Adapter.NG_Adapter;
import com.tomas.pcs_asi.ListData.Get_OutputCode;
import com.tomas.pcs_asi.ListData.NG_Lists;
import com.tomas.pcs_asi.ListData.User_Lists;
import com.tomas.pcs_asi.lib.ConvertStringToCalendar;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.ProductionSchedule;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.Scanner;
import com.tomas.pcs_asi.lib.common.Utils;

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

import java.net.URLDecoder;
import java.net.URLEncoder;
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 RandomCheck_Activity extends Scanner implements View.OnClickListener {
    LinearLayout layout_random_wb, layout_random_mold,layout_spinner, layout_material, layout_equipment, layout_equipment_mold;
    ConstraintLayout layout_lotout, layout_alert;
    TextView txt_header, txt_ics, txt_lot_no, txt_job_order, txt_check_time, txt_machine_no, txt_user_id, txt_scan_ng, txt_leader_lotout,
            txt_message, txt_ics_part, txt_lot_part, txt_equipment_resin, txt_resin_exp, txt_equipment_mold, txt_mold_exp, txt_lot_out,
            txt_equipment_wb, txt_equipment_wb_exp;
    Spinner spinner_status, spinner_status_chip;
    EditText edt_qty, edt_point1, edt_point2, edt_point3,edt_point4, edt_point5, edt_weight1, edt_weight2, edt_weight3, edt_weight4,
            edt_weight5, edt_top1, edt_top2, edt_top3, edt_top4, edt_bottom1, edt_bottom2, edt_bottom3, edt_bottom4, edt_resin_temp;
    RecyclerView view_ng;
    Button  btn_save;
    DecimalFormat decimalFormat;
    NG_Adapter ng_adapter;
    Map<String, Get_OutputCode> map_code_ng;
    Map<String, NG_Lists>map_ng_scan;
    List<NG_Lists> list_ng;
    Double weight_min, weight_max, mold_temp_min, mold_temp_max, resin_temp_min, resin_temp_max;
    boolean lot_out, b_confirm,check_material, nurse_call, scan_part;
    int Max_line_SP, check_time, lotout_time, cavity;
    Bundle bundle;
    Calendar calendar;
    SimpleDateFormat fm_dt_server, dt_format_qr;
    String str_process, str_sch_id, DefectName, broken_point, str_mc_type, str_machine, str_ics, str_job, str_lot_no,
            random_type, random_id, random_check_result, dt_to_server, str_format_dt = "dd/MM/yyyy HH:mm";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random_check);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        decimalFormat = new DecimalFormat("####.00");
        fm_dt_server = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dt_format_qr = new SimpleDateFormat("dd/MM/yyyy HH:mm");

        lot_out = false;
        nurse_call = false;
        check_material = false;
        scan_part = false;
        b_confirm = true;
        weight_min = 0.0;
        weight_max = 0.0;
        mold_temp_min = 0.0; mold_temp_max = 0.0; resin_temp_min = 0.0; resin_temp_max = 0.0;

        list_ng = new ArrayList<NG_Lists>();
        map_code_ng = new LinkedHashMap<>();
        map_ng_scan = new LinkedHashMap<>();

        str_ics = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot_no = Settings.getLotNo();
        str_process = Settings.getPROCESS();

        bundle = getIntent().getExtras();
        random_id = bundle.getString("id");
        str_machine = bundle.getString("machine_code");
        str_sch_id = bundle.getString("sch_id");
        random_type = bundle.getString("random_type");
        String time = bundle.getString("check_time");
        check_time = Integer.parseInt(time);

        Log.d(getString(R.string.tag), "RandomCheck_Activity: " + random_id+" | "+str_sch_id+" | "+time);

        layout_random_wb = (LinearLayout) findViewById(R.id.layout_random_wb);
        layout_random_mold = (LinearLayout) findViewById(R.id.layout_random_mold);
        layout_lotout = (ConstraintLayout) findViewById(R.id.layout_lotout);
        layout_alert = (ConstraintLayout) findViewById(R.id.layout_alert_save);
        layout_spinner = (LinearLayout)findViewById(R.id.layout_spinner);
        layout_material = (LinearLayout)findViewById(R.id.layout_material);
        layout_equipment = (LinearLayout)findViewById(R.id.layout_equipment);
        layout_equipment_mold = (LinearLayout)findViewById(R.id.layout_equipment_mold);
        btn_save = (Button)findViewById(R.id.btn_save);
        spinner_status = (Spinner) findViewById(R.id.spinner_status);
        spinner_status_chip = (Spinner) findViewById(R.id.spinner_status_chip);

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

        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_ics = (TextView) findViewById(R.id.txt_ics);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_check_time = (TextView) findViewById(R.id.txt_check_time);
        txt_machine_no = (TextView) findViewById(R.id.txt_machine_no);
        txt_user_id = (TextView) findViewById(R.id.txt_user_id);
        txt_scan_ng = (TextView) findViewById(R.id.txt_scan_ng);
        txt_leader_lotout = (TextView) findViewById(R.id.txt_leader_lotout);
        txt_message = (TextView) findViewById(R.id.txt_message);
        txt_ics_part = (TextView) findViewById(R.id.txt_ics_part);
        txt_lot_part = (TextView) findViewById(R.id.txt_lot_part);
        txt_equipment_resin = (TextView) findViewById(R.id.txt_equipment_resin);
        txt_resin_exp = (TextView) findViewById(R.id.txt_resin_exp);
        txt_equipment_mold = (TextView) findViewById(R.id.txt_equipment_mold);
        txt_mold_exp = (TextView) findViewById(R.id.txt_mold_exp);
        txt_lot_out = (TextView)findViewById(R.id.txt_lot_out);
        txt_equipment_wb = (TextView)findViewById(R.id.txt_equipment_wb);
        txt_equipment_wb_exp  = (TextView)findViewById(R.id.txt_equipment_wb_exp);

        txt_header.setText(str_process+" Random Check");
        txt_ics.setText("ICS : "+str_ics);
        txt_job_order.setText("JOB ORDER : "+str_job);
        txt_lot_no.setText("LOT NO : "+str_lot_no);
        txt_check_time.setText(String.valueOf(check_time));
        txt_machine_no.setHint(str_machine);

        edt_qty = (EditText) findViewById(R.id.edt_qty);
        edt_point1 = (EditText) findViewById(R.id.edt_point1);
        edt_point2 = (EditText) findViewById(R.id.edt_point2);
        edt_point3 = (EditText) findViewById(R.id.edt_point3);
        edt_point4 = (EditText) findViewById(R.id.edt_point4);
        edt_point5 = (EditText) findViewById(R.id.edt_point5);
        edt_weight1 = (EditText) findViewById(R.id.edt_weight1);
        edt_weight2 = (EditText) findViewById(R.id.edt_weight2);
        edt_weight3 = (EditText) findViewById(R.id.edt_weight3);
        edt_weight4 = (EditText) findViewById(R.id.edt_weight4);
        edt_weight5 = (EditText) findViewById(R.id.edt_weight5);
        edt_top1 = (EditText) findViewById(R.id.edt_top1);
        edt_top2 = (EditText) findViewById(R.id.edt_top2);
        edt_top3 = (EditText) findViewById(R.id.edt_top3);
        edt_top4 = (EditText) findViewById(R.id.edt_top4);
        edt_bottom1 = (EditText) findViewById(R.id.edt_bottom1);
        edt_bottom2 = (EditText) findViewById(R.id.edt_bottom2);
        edt_bottom3 = (EditText) findViewById(R.id.edt_bottom3);
        edt_bottom4 = (EditText) findViewById(R.id.edt_bottom4);
        edt_resin_temp = (EditText) findViewById(R.id.edt_resin_temp);

        edt_qty.requestFocus();
        edt_point1.requestFocus();
        edt_point2.requestFocus();
        edt_point3.requestFocus();
        edt_point4.requestFocus();
        edt_point5.requestFocus();
        edt_weight1.requestFocus();
        edt_weight2.requestFocus();
        edt_weight3.requestFocus();
        edt_weight4.requestFocus();
        edt_weight5.requestFocus();
        edt_top1.requestFocus();
        edt_top2.requestFocus();
        edt_top3.requestFocus();
        edt_top4.requestFocus();
        edt_bottom1.requestFocus();
        edt_bottom2.requestFocus();
        edt_bottom3.requestFocus();
        edt_bottom4.requestFocus();
        edt_resin_temp.requestFocus();

        edt_qty.setShowSoftInputOnFocus(false);
        edt_point1.setShowSoftInputOnFocus(false);
        edt_point2.setShowSoftInputOnFocus(false);
        edt_point3.setShowSoftInputOnFocus(false);
        edt_point4.setShowSoftInputOnFocus(false);
        edt_point5.setShowSoftInputOnFocus(false);
        edt_weight1.setShowSoftInputOnFocus(false);
        edt_weight2.setShowSoftInputOnFocus(false);
        edt_weight3.setShowSoftInputOnFocus(false);
        edt_weight4.setShowSoftInputOnFocus(false);
        edt_weight5.setShowSoftInputOnFocus(false);
        edt_top1.setShowSoftInputOnFocus(false);
        edt_top2.setShowSoftInputOnFocus(false);
        edt_top3.setShowSoftInputOnFocus(false);
        edt_top4.setShowSoftInputOnFocus(false);
        edt_bottom1.setShowSoftInputOnFocus(false);
        edt_bottom2.setShowSoftInputOnFocus(false);
        edt_bottom3.setShowSoftInputOnFocus(false);
        edt_bottom4.setShowSoftInputOnFocus(false);
        edt_resin_temp.setShowSoftInputOnFocus(false);

        //adjust layout
        if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())){
            lotout_time = 3;
            str_mc_type = ProductionSchedule.MACHINE.WB.toString();
            layout_random_wb.setVisibility(View.VISIBLE);
            Get_List_Output("BONDING_INS");
            Get_Item_Master(str_ics);

        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
            lotout_time = 3;
            if (random_type.trim().equals(ProductionSchedule.Random_Type.Shift_Day.toString())
                    || random_type.trim().equals(ProductionSchedule.Random_Type.Shift_Night.toString())){
                layout_random_mold.setVisibility(View.VISIBLE);
                layout_equipment.setVisibility(View.VISIBLE);

            }else if (random_type.trim().equals(ProductionSchedule.Random_Type.ChangeModel.toString())){
                layout_equipment.setVisibility(View.VISIBLE);
                layout_equipment_mold.setVisibility(View.GONE);
            }

            str_mc_type = ProductionSchedule.MACHINE.MOLD.toString();
            Get_List_Output(str_process);
            Get_Machine_Mold(str_machine, str_ics);

        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.DICER.toString())){
            layout_spinner.setVisibility(View.VISIBLE);
            lotout_time = 3;
            str_mc_type = ProductionSchedule.MACHINE.DICER.toString();
            Get_Machine_Dicer(str_machine);
            Get_List_Output(str_process);

        }else {//DIE_BOND
            lotout_time = 3;
            str_mc_type = ProductionSchedule.MACHINE.DB.toString();
            Get_List_Output("BONDING_INS");

            if (random_type.trim().equals(ProductionSchedule.Random_Type.Edit.toString())){
                check_material = true;
                layout_material.setVisibility(View.VISIBLE);
            }
        }
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;
            case R.id.btn_save:
                if (b_confirm == true) {
                    Block_button();
                    Check_Result();
                }
                break;
            case R.id.btn_ok_lotout:
                if (txt_leader_lotout.getText().toString().trim().equals("")){
                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกนรหัสพนักงาน leader!")
                            .show();
                }else {
                    layout_lotout.setVisibility(View.GONE);
                    Update_RandomCheckList();
                }
                break;
            case R.id.btn_cancel_lotout:
                Cancel_LotOut();//P3
                break;
        }
    }
    private void Cancel_LotOut() {
        txt_leader_lotout.setText("");
        lot_out = false;
        nurse_call = false;
        layout_lotout.setVisibility(View.GONE);
        Unblock_button();
    }
    private void Block_button() {
        b_confirm = false;
        btn_save.setEnabled(false);
        btn_save.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_confirm = true;
        btn_save.setEnabled(true);
        btn_save.setBackgroundResource(R.drawable.button_backgroup_green);
    }

    private void Check_Result() {
        if (txt_machine_no.getText().toString().trim().equals("")
            || txt_user_id.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
        }else {
            if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())){
                if (map_ng_scan.size() == 0){
                    random_check_result = "OK";
                }else{
                    random_check_result = "NG";
                }


            }else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())){
                if (edt_point1.getText().toString().trim().equals("")
                    ||edt_point2.getText().toString().trim().equals("")
                    ||edt_point3.getText().toString().trim().equals("")
                    ||edt_point4.getText().toString().trim().equals("")
                    ||edt_point5.getText().toString().trim().equals("")
                    ||edt_weight1.getText().toString().trim().equals("")
                    ||edt_weight2.getText().toString().trim().equals("")
                    ||edt_weight3.getText().toString().trim().equals("")
                    ||edt_weight4.getText().toString().trim().equals("")
                    ||edt_weight5.getText().toString().trim().equals("")
                    ||txt_equipment_wb.getText().toString().trim().equals("")
                    |txt_equipment_wb_exp.getText().toString().trim().equals("")){
                    Unblock_button();
                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณากรอกข้อมูล จุดขาด, น้ำหนัก หรือ equipment ให้ครบ!")
                            .show();
                    return;

                }else {
                    //check broken point
                    String result_point = "";
                    String point1 = edt_point1.getText().toString().trim();
                    String point2 = edt_point2.getText().toString().trim();
                    String point3 = edt_point3.getText().toString().trim();
                    String point4 = edt_point4.getText().toString().trim();
                    String point5 = edt_point5.getText().toString().trim();

                    if (broken_point.contains(point1)){
                        result_point = "NG";
                    }else if (broken_point.contains(point2)){
                        result_point = "NG";
                    }else if (broken_point.contains(point3)){
                        result_point = "NG";
                    }else if (broken_point.contains(point4)){
                        result_point = "NG";
                    }else if (broken_point.contains(point5)){
                        result_point = "NG";
                    }else {
                        result_point = "OK";
                    }
                    //check weight
                    String result_weight= "";
                    Double weight1 = Double.parseDouble(edt_weight1.getText().toString().trim());
                    Double weight2 = Double.parseDouble(edt_weight2.getText().toString().trim());
                    Double weight3 = Double.parseDouble(edt_weight3.getText().toString().trim());
                    Double weight4 = Double.parseDouble(edt_weight4.getText().toString().trim());
                    Double weight5 = Double.parseDouble(edt_weight5.getText().toString().trim());

                    if (weight1 < weight_min || weight1 > weight_max){
                        result_weight = "NG";
                    }else if (weight2 < weight_min || weight2 > weight_max){
                        result_weight = "NG";
                    }else if (weight3 < weight_min || weight3 > weight_max){
                        result_weight = "NG";
                    }else if (weight4 < weight_min || weight4 > weight_max){
                        result_weight = "NG";
                    }else if (weight5 < weight_min || weight5 > weight_max){
                        result_weight = "NG";
                    }else {
                        result_weight = "OK";
                    }

                    if (map_ng_scan.size() == 0
                            && result_point.trim().equals("OK")
                            && result_weight.trim().equals("OK")){
                        random_check_result = "OK";
                    }else{
                        random_check_result = "NG";
                    }
                }
            }else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                if (random_type.trim().equals(ProductionSchedule.Random_Type.Shift_Day.toString())
                    ||random_type.trim().equals(ProductionSchedule.Random_Type.Shift_Night.toString())){//shift day / shift night

                    String result_temp_mold = "", result_temp_resin = "";

                    //Check temperature resin
                    if (resin_temp_min > 0 && resin_temp_max > 0){//mold manual
                        if (txt_equipment_resin.getText().toString().trim().equals("")
                            || txt_resin_exp.getText().toString().trim().equals("")
                            || edt_resin_temp.getText().toString().trim().equals("")) {
                            Unblock_button();
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("กรุณากรอกข้อมูลเรซิ่นให้ครบ!")
                                    .show();
                            return;

                        }else {
                            Double resin_temp = Double.parseDouble(edt_resin_temp.getText().toString().trim());
                            //Check temperature resin
                            if (resin_temp < resin_temp_min || resin_temp > resin_temp_max){
                                result_temp_resin = "NG";

                            }else {
                                result_temp_resin = "OK";
                            }
                        }
                    }else {//mold auto
                        result_temp_resin = "OK";
                    }

                    //Check temperature mold
                            switch (cavity) {
                                case 1:
                                    if (edt_top1.getText().toString().trim().equals("")
                                            || edt_bottom1.getText().toString().trim().equals("")) {
                                        Unblock_button();
                                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("กรุณาอุณหภูมิแม่พิมพ์ให้ครบ 1 เบ้า บน/ล่าง")
                                                .show();
                                        return;
                                    } else {
                                        Double top1 = Double.parseDouble(edt_top1.getText().toString().trim());
                                        Double bottom1 = Double.parseDouble(edt_bottom1.getText().toString().trim());
                                        if (top1 < mold_temp_min || top1 > mold_temp_max || bottom1 < mold_temp_min || bottom1 > mold_temp_max) {
                                            result_temp_mold = "NG";
                                        } else {
                                            result_temp_mold = "OK";
                                        }
                                    }
                                    break;
                                case 2:
                                    if (edt_top1.getText().toString().trim().equals("")
                                            || edt_top2.getText().toString().trim().equals("")
                                            || edt_bottom1.getText().toString().trim().equals("")
                                            || edt_bottom2.getText().toString().trim().equals("")) {
                                        Unblock_button();
                                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("กรุณากรอกข้อมูลให้ครบทั้ง 2 เบ้า บน/ล่าง")
                                                .show();
                                        return;
                                    } else {
                                        Double top1 = Double.parseDouble(edt_top1.getText().toString().trim());
                                        Double top2 = Double.parseDouble(edt_top2.getText().toString().trim());
                                        Double bottom1 = Double.parseDouble(edt_bottom1.getText().toString().trim());
                                        Double bottom2 = Double.parseDouble(edt_bottom2.getText().toString().trim());

                                        if (top1 < mold_temp_min || top1 > mold_temp_max || bottom1 < mold_temp_min || bottom1 > mold_temp_max
                                                || top2 < mold_temp_min || top2 > mold_temp_max || bottom2 < mold_temp_min || bottom2 > mold_temp_max) {
                                            result_temp_mold = "NG";
                                        } else {
                                            result_temp_mold = "OK";
                                        }
                                    }

                                    break;
                                case 3:
                                    if (edt_top1.getText().toString().trim().equals("")
                                            || edt_top2.getText().toString().trim().equals("")
                                            || edt_top3.getText().toString().trim().equals("")
                                            || edt_bottom1.getText().toString().trim().equals("")
                                            || edt_bottom2.getText().toString().trim().equals("")
                                            || edt_bottom3.getText().toString().trim().equals("")) {
                                        Unblock_button();
                                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("กรุณากรอกข้อมูลให้ครบทั้ง 3 เบ้า บน/ล่าง")
                                                .show();
                                        return;
                                    } else {
                                        Double top1 = Double.parseDouble(edt_top1.getText().toString().trim());
                                        Double top2 = Double.parseDouble(edt_top2.getText().toString().trim());
                                        Double top3 = Double.parseDouble(edt_top3.getText().toString().trim());
                                        Double bottom1 = Double.parseDouble(edt_bottom1.getText().toString().trim());
                                        Double bottom2 = Double.parseDouble(edt_bottom2.getText().toString().trim());
                                        Double bottom3 = Double.parseDouble(edt_bottom3.getText().toString().trim());

                                        if (top1 < mold_temp_min || top1 > mold_temp_max || bottom1 < mold_temp_min || bottom1 > mold_temp_max
                                                || top2 < mold_temp_min || top2 > mold_temp_max || bottom2 < mold_temp_min || bottom2 > mold_temp_max
                                                || top3 < mold_temp_min || top3 > mold_temp_max || bottom3 < mold_temp_min || bottom3 > mold_temp_max) {
                                            result_temp_mold = "NG";
                                        } else {
                                            result_temp_mold = "OK";
                                        }
                                    }
                                    break;
                                case 4:
                                    if (edt_top1.getText().toString().trim().equals("")
                                            || edt_top2.getText().toString().trim().equals("")
                                            || edt_top3.getText().toString().trim().equals("")
                                            || edt_top4.getText().toString().trim().equals("")
                                            || edt_bottom1.getText().toString().trim().equals("")
                                            || edt_bottom2.getText().toString().trim().equals("")
                                            || edt_bottom3.getText().toString().trim().equals("")
                                            || edt_bottom4.getText().toString().trim().equals("")) {
                                        Unblock_button();
                                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("แจ้งเตือน")
                                                .setContentText("กรุณากรอกข้อมูลให้ครบทั้ง 4 เบ้า บน/ล่าง")
                                                .show();
                                        return;
                                    } else {
                                        Double top1 = Double.parseDouble(edt_top1.getText().toString().trim());
                                        Double top2 = Double.parseDouble(edt_top2.getText().toString().trim());
                                        Double top3 = Double.parseDouble(edt_top3.getText().toString().trim());
                                        Double top4 = Double.parseDouble(edt_top4.getText().toString().trim());
                                        Double bottom1 = Double.parseDouble(edt_bottom1.getText().toString().trim());
                                        Double bottom2 = Double.parseDouble(edt_bottom2.getText().toString().trim());
                                        Double bottom3 = Double.parseDouble(edt_bottom3.getText().toString().trim());
                                        Double bottom4 = Double.parseDouble(edt_bottom4.getText().toString().trim());
                                        if (top1 < mold_temp_min || top1 > mold_temp_max || bottom1 < mold_temp_min || bottom1 > mold_temp_max
                                                || top2 < mold_temp_min || top2 > mold_temp_max || bottom2 < mold_temp_min || bottom2 > mold_temp_max
                                                || top3 < mold_temp_min || top3 > mold_temp_max || bottom3 < mold_temp_min || bottom3 > mold_temp_max
                                                || top4 < mold_temp_min || top4 > mold_temp_max || bottom4 < mold_temp_min || bottom4 > mold_temp_max) {
                                            result_temp_mold = "NG";
                                        } else {
                                            result_temp_mold = "OK";
                                        }
                                    }

                                    break;
                            }

                        if (map_ng_scan.size() == 0 && result_temp_mold.trim().equals("OK") && result_temp_resin.trim().equals("OK")) {
                            random_check_result = "OK";
                        } else {
                            random_check_result = "NG";
                        }
                }else if (random_type.trim().equals(ProductionSchedule.Random_Type.ChangeModel.toString())) {
                    String result_temp_resin = "";

                    //Check temperature resin
                    if (resin_temp_min > 0 && resin_temp_max > 0){//mold manual
                        if (txt_equipment_resin.getText().toString().trim().equals("")
                                || txt_resin_exp.getText().toString().trim().equals("")
                                || edt_resin_temp.getText().toString().trim().equals("")) {
                            Unblock_button();
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("กรุณากรอกข้อมูลเรซิ่นให้ครบ!")
                                    .show();
                            return;

                        }else {
                            Double resin_temp = Double.parseDouble(edt_resin_temp.getText().toString().trim());
                            //Check temperature resin
                            if (resin_temp < resin_temp_min || resin_temp > resin_temp_max){
                                result_temp_resin = "NG";

                            }else {
                                result_temp_resin = "OK";
                            }
                        }
                    }else {//mold auto
                        result_temp_resin = "OK";
                    }

//                    if (txt_equipment_resin.getText().toString().trim().equals("")
//                        || txt_resin_exp.getText().toString().trim().equals("")
//                        || edt_resin_temp.getText().toString().trim().equals("")){
//                        Unblock_button();
//                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                .setTitleText("แจ้งเตือน")
//                                .setContentText("กรุณากรอกข้อมูลเรซิ่นให้ครบ!")
//                                .show();
//                        return;
//                    }else {
//                        Double resin_temp = Double.parseDouble(edt_resin_temp.getText().toString().trim());
//
                        if (map_ng_scan.size() == 0 && result_temp_resin.trim().equals("OK")) {
                            random_check_result = "OK";

                        } else {
                            random_check_result = "NG";
                        }
//                    }
                }else {//frequency & NG_MOLD
                    if (map_ng_scan.size() == 0){
                        random_check_result = "OK";
                    }else{
                        random_check_result = "NG";
                    }
                }

            }else {//dicer
                if (spinner_status.getSelectedItem().toString().trim().equals("")){
                    Unblock_button();
                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาเลือกสถานะแนวการตัด!")
                            .show();
                    return;
                }else {
                    if (map_ng_scan.size() == 0 && spinner_status.getSelectedItem().toString().trim().equals("OK")) {
                        random_check_result = "OK";
                    } else {
                        random_check_result = "NG";
                    }
                }
            }

            if (spinner_status_chip.getSelectedItem().toString().equals("NG")){
                random_check_result = "NG";
                //nurse call but no update lotout;
                nurse_call = true;
                lot_out = false;
                txt_lot_out.setText("Nurse Call");
                layout_lotout.setVisibility(View.VISIBLE);
            }else if (check_time >= lotout_time && random_check_result.trim().equals("NG")){
                if (str_process.trim().equals(ProductionSchedule.PROCESS.DICER.toString())){//Nurse Call
                    nurse_call = true;
                    lot_out = false;
                    txt_lot_out.setText("Nurse Call");
                }else {//lotout
                    nurse_call = false;
                    lot_out = true;
                    txt_lot_out.setText("LOT OUT");
                }
                layout_lotout.setVisibility(View.VISIBLE);

            }else {
                Update_RandomCheckList();
            }
        }
    }



    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data scan: " + data);
            String[] tokens = data.trim().split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
            if (tokens.length == 2) {
                Calendar now = Calendar.getInstance();
                Calendar now_dt = (Calendar) now.clone();
                Log.d(getString(R.string.tag), "now_dt: " + now_dt);
                if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())){
                    if (random_type.trim().equals(ProductionSchedule.Random_Type.Shift_Day.toString())
                        || random_type.trim().equals(ProductionSchedule.Random_Type.Shift_Night.toString())){
                        if (tokens[0].substring(0,1).equals("R")){
                            if (!tokens[1].trim().equals("")) {//check exp
                                Calendar resin_exp = ConvertStringToCalendar.convert(tokens[1].trim(), str_format_dt);
                                String str_resin_exp = dt_format_qr.format(resin_exp.getTime());
                                Log.d(getString(R.string.tag), "resin_exp: " + str_resin_exp);

                                if (now_dt.before(resin_exp)){
                                    txt_equipment_resin.setText(tokens[0].trim());
                                    txt_resin_exp.setText(tokens[1].trim());
                                }else {
                                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("เรซิ่นหมดอายุ \n"+tokens[1])
                                            .show();
                                }
                            }else {
                                txt_equipment_resin.setText(tokens[0].trim());
                                txt_resin_exp.setText(tokens[1].trim());
                            }

                        }else if (tokens[0].substring(0,1).equals("M")){
                            if (!tokens[1].trim().equals("")) {//check exp
                                Calendar mold_exp = ConvertStringToCalendar.convert(tokens[1].trim(), str_format_dt);
                                String str_mold_exp = dt_format_qr.format(mold_exp.getTime());
                                Log.d(getString(R.string.tag), "str_mold_exp: " + str_mold_exp);

                                if (now_dt.before(mold_exp)){
                                    txt_equipment_mold.setText(tokens[0].trim());
                                    txt_mold_exp.setText(tokens[1].trim());
                                }else {
                                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("mold หมดอายุ \n"+tokens[1])
                                            .show();
                                }
                            }else {
                                txt_equipment_mold.setText(tokens[0].trim());
                                txt_mold_exp.setText(tokens[1].trim());
                            }
                        }else {
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("QR code ไม่ถูกต้อง!")
                                    .show();
                        }

                    }else if (random_type.trim().equals(ProductionSchedule.Random_Type.ChangeModel.toString())){//resin
                        if (tokens[0].substring(0,1).equals("R")){
                            txt_equipment_resin.setText(tokens[0].trim());
                            txt_resin_exp.setText(tokens[1].trim());

                        }else{
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("QR code ไม่ถูกต้อง!")
                                    .show();
                        }
                    }else {
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("QR code ไม่ถูกต้อง!")
                                .show();
                    }
                }else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())){
                    if (!tokens[1].trim().equals("")) {
                            Calendar equipment_exp = ConvertStringToCalendar.convert(tokens[1].trim(), str_format_dt);
                            String str_equipment_exp = dt_format_qr.format(equipment_exp.getTime());
                            Log.d(getString(R.string.tag), "str_equipment_exp: " + str_equipment_exp);

                            if (now_dt.before(equipment_exp)){
                                txt_equipment_wb.setText(tokens[0]);
                                txt_equipment_wb_exp.setText(tokens[1]);
                            }else {
                                new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("equipment หมดอายุ \n"+tokens[1])
                                        .show();
                            }
                        }else {
                            txt_equipment_wb.setText(tokens[0].trim());
                            txt_equipment_wb_exp.setText(tokens[1].trim());
                        }
                } else {
                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR code ไม่ถูกต้อง!")
                            .show();
                }
            }else {
                if (scan_part == true) {
                    if (txt_ics_part.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาสแกน ICS Code!")
                                .show();
                    } else {
                        scan_part = false;
                        txt_lot_part.setText(data.trim());
                    }
                }else if (data.trim().substring(0, 2).equals("NG")) {
                    if (edt_qty.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณาใส่จำนวน NG")
                                .show();
                    } else {
                        if (map_code_ng.containsKey(data.trim())) {
                            if (map_ng_scan.containsKey(data.trim())) {//ng code duplicate -->del
                                map_ng_scan.remove(data.trim());
                                Set_View_NG_Scan();

                            } else {//add map ng_list
                                txt_scan_ng.setText(data.trim());
                                Add_map_ng_scan(data.trim(), "");
                            }
                        } else {
                            txt_scan_ng.setText("");
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ NG code!")
                                    .show();
                        }
                    }

                } else if (data.trim().contains(str_mc_type)) {//scan machine
                    //check matching machine
                    if (str_machine.trim().equals(data.trim())) {
                        txt_machine_no.setText(data.trim());

                    } else {
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("หมายเลขเครื่องจักรไม่ถูกต้อง")
                                .show();
                    }

                } else if (data.trim().length() == 6) {//scan user
                    Check_User(data.trim());

                } else if(data.trim().length() == 10){
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())){
                        scan_part = true;
                        txt_ics_part.setText(data.trim());

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

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

        }
    }

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){

            if (lot_out == true || nurse_call == true){//scan leader
                User_Lists lists = Settings.getMap_user().get(data);
                String role = lists.getRole();
                Log.d(getString(R.string.tag), "str_role : " + role);

                if (role.trim().equals("LEADER")){
                    txt_leader_lotout.setText(data);

                }else {
                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!!")
                            .show();
                }
            }else {
                if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())
                        && Settings.getMap_user().get(data).getDiebond().trim().equals("1")){
                    txt_user_id.setText(data);

                }else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())
                        && Settings.getMap_user().get(data).getWirebond().trim().equals("1")) {
                    txt_user_id.setText(data);

                }else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())
                        && Settings.getMap_user().get(data).getMold().trim().equals("1")) {
                    txt_user_id.setText(data);

                }else if (str_process.trim().equals(ProductionSchedule.PROCESS.DICER.toString())
                        && Settings.getMap_user().get(data).getDicer().trim().equals("1")) {
                    txt_user_id.setText(data);

                }else {
                    txt_user_id.setText("");
                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่อนุญาตให้ทำงานใน "+str_process)
                            .show();
                }
            }
        }else {
            txt_user_id.setText("");
            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    private void Add_map_ng_scan(String ng_code, String nurse_call) {
        Log.d(getString(R.string.tag), "Add_map_ng_scan : " + ng_code + "|" + nurse_call+"|"+str_process);

        Get_OutputCode outputCode = map_code_ng.get(ng_code);
        map_ng_scan.put(ng_code, new NG_Lists(
                str_sch_id,
                outputCode.getCode(),
                outputCode.getName(),
                edt_qty.getText().toString().trim(),
                str_process,
                nurse_call,
                outputCode.getCalculate()));
        Log.e(getString(R.string.tag), "map_ng_scan: " + map_ng_scan.size());

        Set_View_NG_Scan();
        txt_scan_ng.setText("");
        edt_qty.setText("");
    }

    private void Set_View_NG_Scan() {
        list_ng.clear();
        for (String key : map_ng_scan.keySet()){
            NG_Lists lists = map_ng_scan.get(key);
            list_ng.add(new NG_Lists(
                    lists.getSch_id(),
                    lists.getNg_code(),
                    lists.getNg_name(),
                    lists.getNg_qty(),
                    lists.getProcess(),
                    lists.getNurse_call_user_id(),
                    lists.getCalculate()));
        }
        ng_adapter = new NG_Adapter(list_ng, RandomCheck_Activity.this,"");
        view_ng.setAdapter(ng_adapter);
        Log.d(getString(R.string.tag), "setAdapter" + map_ng_scan.size());
    }

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

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/item.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);
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("ไม่พบ Item Master!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                String str_min = jArray.getJSONObject(i).getString("weight_min").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("weight_min").trim();
                                String str_max = jArray.getJSONObject(i).getString("weight_max").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("weight_max").trim();
                                broken_point = jArray.getJSONObject(i).getString("broken_point").trim() == "null" ? "" : jArray.getJSONObject(i).getString("broken_point").trim();

                                weight_min = Double.parseDouble(str_min);
                                weight_max = Double.parseDouble(str_max);

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

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

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

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

            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);
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบเครื่องจักร!")
                                    .show();
                        }else {
//                            for (int i = 0; i < jArray.length(); i++) {
                                String str_line_SP = jArray.getJSONObject(0).getString("Max_line_SP").trim() == "null" ? "0" : jArray.getJSONObject(0).getString("Max_line_SP").trim();
                                Max_line_SP = Integer.parseInt(str_line_SP.trim().equals("")?"0":str_line_SP);

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

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_mc_mold");
            json.put("machine_code", Machine);
            json.put("ics_code", ics_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);
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบข้อมูลอุณหภูมิของเครื่องจักร!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                String str_mold_temp_min = jArray.getJSONObject(i).getString("mold_temp_min").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("mold_temp_min").trim();
                                String str_mold_temp_max = jArray.getJSONObject(i).getString("mold_temp_max").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("mold_temp_max").trim();
                                String str_resin_temp_min = jArray.getJSONObject(i).getString("resin_temp_min").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("resin_temp_min").trim();
                                String str_resin_temp_max= jArray.getJSONObject(i).getString("resin_temp_max").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("resin_temp_max").trim();
                                String str_Cavity = jArray.getJSONObject(i).getString("Cavity").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Cavity").trim();

                                mold_temp_min = Double.parseDouble(str_mold_temp_min.trim().equals("")?"0":str_mold_temp_min);
                                mold_temp_max = Double.parseDouble(str_mold_temp_max.trim().equals("")?"0":str_mold_temp_max);
                                resin_temp_min = Double.parseDouble(str_resin_temp_min.trim().equals("")?"0":str_resin_temp_min);
                                resin_temp_max = Double.parseDouble(str_resin_temp_max.trim().equals("")?"0":str_resin_temp_max);
                                cavity = Integer.parseInt(str_Cavity.trim().equals("")?"0":str_Cavity);
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/output_code.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);
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ NG Code!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                try {
                                    DefectName =  jArray.getJSONObject(i).getString("DefectName").trim();
                                    Log.d(getString(R.string.tag), "DefectName: " + DefectName);
                                    DefectName =  URLDecoder.decode(DefectName, "UTF-8");
                                    Log.d(getString(R.string.tag), "DefectName_decode: " + DefectName);

                                }catch (Exception e){
                                    layout_alert.setVisibility(View.GONE);
                                    new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                            .setTitleText("ERROR")
                                            .setContentText(e.getMessage())
                                            .show();
                                }
                                map_code_ng.put(jArray.getJSONObject(i).getString("Code").trim(),
                                        new Get_OutputCode(
                                                jArray.getJSONObject(i).getString("Process").trim(),
                                                jArray.getJSONObject(i).getString("Code").trim(),
                                                DefectName,
                                                jArray.getJSONObject(i).getString("Status").trim(),
                                                jArray.getJSONObject(i).getString("NurseCall").trim(),
                                                jArray.getJSONObject(i).getString("Calculate").trim()));
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_code_ng.size()));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "update_randomcheck");
            json.put("id", random_id);
            json.put("user_id", txt_user_id.getText().toString().trim());
            json.put("result", random_check_result);
            json.put("sch_id", str_sch_id);
            json.put("machine_code", txt_machine_no.getText().toString().trim());
            json.put("process", str_process);
            json.put("random_type", random_type);
            json.put("check_time", check_time+1);
            json.put("nurse_call_user_id", txt_leader_lotout.getText().toString().trim());
            json.put("lot_out",lot_out);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/random_check.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").trim();
                        String message = jsonObject.getString("message").trim();

                        if (status.trim().equals("error")){
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(message)
                                    .show();
                        }else {//success :
                                if (random_check_result.trim().equals("OK")) {
                                    // Discard the ScanManager class instance.
                                    mScanManager.removeDataListener(RandomCheck_Activity.this);
                                    // Discard the ScanManager class instance to release the resources.
                                    mScanManager.releaseScanManager();
                                    if ((str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString()) && check_material == false)
                                        ||(str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString()) && random_type.trim().equals(ProductionSchedule.Random_Type.Frequency.toString()))) {

                                        finish();
                                    }else {//diebond : edit;  mold : check_temp == true; for insert temperature
                                        Insert_RandomCheck_Detail(message);
                                    }
                                }else {//NG
                                    if (map_ng_scan.size() == 0){
                                        Insert_RandomCheck_Detail(message);

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

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

    }

    private void Insert_RandomCheck_NG(String message) {
        Block_button();
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();

            for (String key : map_ng_scan.keySet()){
                NG_Lists lists = map_ng_scan.get(key);

                String ng = lists.getNg_name();
                String ng_name = URLEncoder.encode(ng,"UTF-8");

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("sch_id", lists.getSch_id());
                jsonParams.put("random_check_id", random_id);
                jsonParams.put("ng_code", lists.getNg_code());
                jsonParams.put("ng_name", ng_name);
                jsonParams.put("qty", lists.getNg_qty());
                jsonParams.put("process", lists.getProcess());
                jsonParams.put("create_dt", dt_to_server);
                jsonParams.put("create_user_id", txt_user_id.getText().toString().trim());
                JSONObject jsonObj = new JSONObject(jsonParams);
                jsonArray.put(jsonObj);
            }
            json.put("ng_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/random_check_ng.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);
                        Log.d(getString(R.string.tag), "response : " + response);

                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        String error = jsonObject.getString("error").trim();

                        if (status.equals("success") && affected_rows > 0) {//success
                            if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())
                            ||(str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString()) && random_type.trim().equals(ProductionSchedule.Random_Type.Frequency.toString()))) {
                                String title;
                                if (lot_out == false){
                                    title = "ต้องสุ่มตรวจสอบอีกครั้ง";
                                }else {
                                    title = "แจ้งเตือนสถานะงาน LOTOUT";
                                }

                                SweetAlertDialog pDialog = new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE);
                                pDialog.setTitleText(title);
                                pDialog.setContentText(message);
                                pDialog.setCancelable(false);
                                pDialog.setContentText("รับทราบ");
                                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                        finish();
                                    }
                                });
                                pDialog.show();
                            }else {//wb, mold:check_temp == true, dicer
                                Insert_RandomCheck_Detail(message);
                            }
                        }else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_RandomCheck_Detail(String message) {
        if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())
            && txt_ics_part.getText().toString().trim().equals("")
            && txt_lot_part.getText().toString().trim().equals("")
            && spinner_status_chip.getSelectedItem().toString().trim().equals("")){
            finish();
        }else {
            try {
                layout_alert.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "add");
                json.put("random_check_id", random_id);
                json.put("create_user_id", txt_user_id.getText().toString().trim());
                json.put("process", str_process);
                json.put("point1", edt_point1.getText().toString().trim().equals("") ? "null" : edt_point1.getText().toString().trim());
                json.put("point2", edt_point2.getText().toString().trim().equals("") ? "null" : edt_point2.getText().toString().trim());
                json.put("point3", edt_point3.getText().toString().trim().equals("") ? "null" : edt_point3.getText().toString().trim());
                json.put("point4", edt_point4.getText().toString().trim().equals("") ? "null" : edt_point4.getText().toString().trim());
                json.put("point5", edt_point5.getText().toString().trim().equals("") ? "null" : edt_point5.getText().toString().trim());
                json.put("weight1", edt_weight1.getText().toString().trim().equals("") ? "null" : edt_weight1.getText().toString().trim());
                json.put("weight2", edt_weight2.getText().toString().trim().equals("") ? "null" : edt_weight2.getText().toString().trim());
                json.put("weight3", edt_weight3.getText().toString().trim().equals("") ? "null" : edt_weight3.getText().toString().trim());
                json.put("weight4", edt_weight4.getText().toString().trim().equals("") ? "null" : edt_weight4.getText().toString().trim());
                json.put("weight5", edt_weight5.getText().toString().trim().equals("") ? "null" : edt_weight5.getText().toString().trim());
                json.put("wirebond_equipment", txt_equipment_wb.getText().toString().trim().equals("") ? "null" : txt_equipment_wb.getText().toString().trim());
                json.put("wirebond_equipment_exp", txt_equipment_wb_exp.getText().toString().trim().equals("") ? "null" : txt_equipment_wb_exp.getText().toString().trim());
                json.put("temp_top1", edt_top1.getText().toString().trim().equals("") ? "null" : edt_top1.getText().toString().trim());
                json.put("temp_top2", edt_top2.getText().toString().trim().equals("") ? "null" : edt_top2.getText().toString().trim());
                json.put("temp_top3", edt_top3.getText().toString().trim().equals("") ? "null" : edt_top3.getText().toString().trim());
                json.put("temp_top4", edt_top4.getText().toString().trim().equals("") ? "null" : edt_top4.getText().toString().trim());
                json.put("temp_bottom1", edt_bottom1.getText().toString().trim().equals("") ? "null" : edt_bottom1.getText().toString().trim());
                json.put("temp_bottom2", edt_bottom2.getText().toString().trim().equals("") ? "null" : edt_bottom2.getText().toString().trim());
                json.put("temp_bottom3", edt_bottom3.getText().toString().trim().equals("") ? "null" : edt_bottom3.getText().toString().trim());
                json.put("temp_bottom4", edt_bottom4.getText().toString().trim().equals("") ? "null" : edt_bottom4.getText().toString().trim());
                json.put("mold_equipment", txt_equipment_mold.getText().toString().trim().equals("") ? "null" : txt_equipment_mold.getText().toString().trim());
                json.put("mold_exp", txt_mold_exp.getText().toString().trim().equals("") ? "null" : txt_mold_exp.getText().toString().trim());
                json.put("resin_equipment", txt_equipment_resin.getText().toString().trim().equals("") ? "null" : txt_equipment_resin.getText().toString().trim());
                json.put("resin_exp", txt_resin_exp.getText().toString().trim().equals("") ? "null" : txt_resin_exp.getText().toString().trim());
                json.put("resin_temp", edt_resin_temp.getText().toString().trim().equals("") ? "null" : edt_resin_temp.getText().toString().trim());
                json.put("cutting_line", spinner_status.getSelectedItem().toString().trim().equals("") ? "null" : spinner_status.getSelectedItem().toString().trim());
                json.put("material", txt_ics_part.getText().toString().trim().equals("") ? "null" : txt_ics_part.getText().toString().trim());
                json.put("material_lot_no", txt_lot_part.getText().toString().trim().equals("") ? "null" : txt_lot_part.getText().toString().trim());
                json.put("material_status", spinner_status_chip.getSelectedItem().toString().trim().equals("") ? "null" : spinner_status_chip.getSelectedItem().toString().trim());

                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/random_check_detail.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").trim();
                            String error = jsonObject.getString("error").trim();
                            int affected_rows = jsonObject.getInt("affected_rows");

                            if (status.equals("success") && affected_rows > 0) {
                                if (random_check_result.trim().equals("OK")) {
                                    finish();
                                } else {
                                    SweetAlertDialog pDialog = new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE);
                                    pDialog.setTitleText("แจ้งเตือนการสุ่มตรวจสอบอีกครั้ง");
                                    pDialog.setContentText(message);
                                    pDialog.setCancelable(false);
                                    pDialog.setConfirmText("รับทราบ");
                                    pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                            finish();
                                        }
                                    });
                                    pDialog.show();
                                }
                            } else {
                                new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText(error)
                                        .show();
                            }
                        } catch (JSONException e) {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();

            } catch (JSONException e) {
                Unblock_button();
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(RandomCheck_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_confirm == true) {
                        Block_button();
                        Check_Result();

                    }else if (lot_out == true || nurse_call == true){
                        if (txt_leader_lotout.getText().toString().trim().equals("")){
                            new SweetAlertDialog(RandomCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("กรุณาสแกนรหัสพนักงาน leader!")
                                    .show();
                        }else {
                            layout_lotout.setVisibility(View.GONE);
                            Update_RandomCheckList();
                        }
                    }
                    break;
                case P3:
                    if (lot_out == true || nurse_call == true){
                        Cancel_LotOut();//P3
                    }
                    break;
            }
        }

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