package com.tomas.pcs_asi;

import androidx.appcompat.app.AppCompatActivity;
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 android.content.Intent;
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.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

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.Item_Classify;
import com.tomas.pcs_asi.ListData.Item_Dicer;
import com.tomas.pcs_asi.ListData.NG_Lists;
import com.tomas.pcs_asi.ListData.Output_Lists;
import com.tomas.pcs_asi.ListData.User_Lists;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.MyAlert;
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.SimpleDateFormat;
import java.util.ArrayList;
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 Classify_Output_Activity extends Scanner implements View.OnClickListener {
    TextView txt_ics,txt_lot_cls, txt_user, txt_scan_output, txt_qty_ng, txt_input, txt_output, txt_message, txt_leader, txt_nurse, txt_leader_lotout;
    EditText edt_qty, edt_remark;
    LinearLayout layout_scan_output, layout_output, layout_sum, layout_btn_finish, layout_btn_confirm, layout_remark;
    ConstraintLayout layout_alert, layout_nurse_call, layout_lotout;
    ScrollView layout_cls_output;
    String str_cls_lot, str_ics, str_input_cls, str_role, str_leader, str_output_code, str_cls_rank, dt_to_server, DefectName;
    Calendar calendar;
    RecyclerView view_cls_output;
    SimpleDateFormat fm_dt_server;
     boolean  nurse_call, scanner, confirm, lot_out, b_confirm;
    Map<String, Get_OutputCode> map_code_ng;
    Map<String, Output_Lists>map_output_scan;
    List<NG_Lists> list_ng;
    NG_Adapter ng_adapter;
    int sum_ok, sum_ng, int_ok, int_ng, sum;
    Button btn_confirm;

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

        nurse_call = false;
        scanner = true;
        confirm = false;
        lot_out = false;
        b_confirm = true;

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

        layout_lotout = (ConstraintLayout)findViewById(R.id.layout_lotout);
        txt_leader_lotout = (TextView)findViewById(R.id.txt_leader_lotout);

        layout_scan_output = (LinearLayout)findViewById(R.id.layout_scan_output);
//        layout_output = (LinearLayout)findViewById(R.id.layout_output);
        layout_sum = (LinearLayout)findViewById(R.id.layout_sum);
        layout_btn_finish = (LinearLayout)findViewById(R.id.layout_btn_finish);
        layout_btn_confirm = (LinearLayout)findViewById(R.id.layout_btn_confirm);
        layout_remark = (LinearLayout)findViewById(R.id.layout_remark);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_nurse_call = (ConstraintLayout) findViewById(R.id.layout_nurse_call);
        layout_cls_output = (ScrollView)findViewById(R.id.scrollview);

        btn_confirm = (Button)findViewById(R.id.btn_confirm);
        txt_ics = (TextView) findViewById(R.id.txt_ics);
        txt_lot_cls = (TextView) findViewById(R.id.txt_lot_cls);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_scan_output = (TextView) findViewById(R.id.txt_scan_output);
        txt_qty_ng = (TextView) findViewById(R.id.txt_qty_ng);
        txt_input = (TextView) findViewById(R.id.txt_input);
        txt_output = (TextView) findViewById(R.id.txt_output);
        txt_message = (TextView) findViewById(R.id.txt_message);
        txt_leader = (TextView) findViewById(R.id.txt_leader);
        txt_nurse = (TextView)findViewById(R.id.txt_nurse);

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

        edt_remark = (EditText) findViewById(R.id.edt_remark);

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

        str_cls_lot = Settings.getClsLot();
        str_ics = Settings.getICS();

        txt_lot_cls.setText(str_cls_lot);
        txt_ics.setText(str_ics);

        Log.d(getString(R.string.tag), "Classify Output Activity : " + str_cls_lot+" | "+ str_ics);

        Get_Qty_input();
        Get_List_Output(ProductionSchedule.PROCESS.CLASSIFY.toString());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                if (confirm == true){
                    Return_Layout();
                }else {
                    Intent intent = new Intent(Classify_Output_Activity.this, Search_ProcessSheet_Lot_Activity.class);
                    startActivity(intent);
                    finish();
                }
                break;

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

            case R.id.btn_finish:
                Set_layout_View();
                break;

            case R.id.btn_confirm:
                if (b_confirm == true) {
                    Block_button();
                    Check_Output();
                }
                break;

            case R.id.btn_ok_nurse_call:
                OK_NurseCall();
                break;

            case R.id.btn_cancel_nurse_call:
                Cancel_NurseCall();
                break;

            case R.id.btn_ok_lotout:
                if (b_confirm == true) {
                    Block_button();
                    Update_Output();
                }
                break;

            case R.id.btn_cancel_lotout:
                Cancel_LotOut();
                break;

        }
    }

    private void Block_button() {
        b_confirm = false;
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

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

    private void Clear_Output() {
        map_output_scan.clear();
        Set_View_Scan();
    }

    private void Update_Output() {
        if (txt_leader_lotout.getText().toString().trim().equals("")) {
            Unblock_button();
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please scan user id!")
                    .show();
        } else {
            layout_lotout.setVisibility(View.GONE);
            Update_CLS_finish();
        }
    }

    private void Cancel_LotOut() {//P3
        txt_leader_lotout.setText("");
        lot_out = false;
        layout_lotout.setVisibility(View.GONE);
        Unblock_button();
    }

    private void Check_Output() {
        int i_output;
        if (txt_output.getText().toString().trim().equals("")){
            i_output = 0;
        }else{
            String str_output = txt_output.getText().toString().trim();
            i_output = Integer.parseInt(str_output);
        }

        if (i_output <= 0){
            Unblock_button();
                lot_out = true;
                layout_lotout.setVisibility(View.VISIBLE);
        }else {
            Update_CLS_finish();
        }
    }

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

        try {
            Log.d(getString(R.string.tag), "scan data : " + data);

           if (lot_out == true){
                if (data.trim().length() == 6){
                    Check_User(data.trim());

                }else {
                    new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Invalid QR code!")
                            .show();
                }
            }else if (scanner == false) {
                return;
            }else{
                if (data.trim().substring(0,2).trim().equals("NG") || data.trim().contains("BOX")){
                    if (edt_qty.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Please Enter qty NG")
                                .show();
                    } else {
                        str_output_code = data.trim();
                        if (data.trim().substring(0,2).trim().equals("NG")){
                            if (map_code_ng.containsKey(str_output_code)){
                                if (map_output_scan.containsKey(str_output_code)){//code duplicate -->del
                                    map_output_scan.remove(str_output_code);
                                    Set_View_Scan();
                                }else {
                                    txt_scan_output.setText(str_output_code);
                                    Get_OutputCode outputCode = map_code_ng.get(str_output_code);
                                    String s_nurse_call = outputCode.getNurse_call();

                                    if (s_nurse_call.trim().equals("1")) {
                                        nurse_call = true;
                                        layout_cls_output.setVisibility(View.GONE);
                                        layout_nurse_call.setVisibility(View.VISIBLE);

                                    } else {
                                        Get_OutputCode list = map_code_ng.get(str_output_code);
                                        String name = list.getName();

                                        Add_map_scan(str_output_code, name,"NG", "");
                                    }
                                }
                            }else {
                                txt_scan_output.setText("");
                                new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("NG code not found!")
                                        .show();
                            }
                        } else if (data.trim().contains("BOX")) {
                            str_output_code = data.trim();
                            if (map_output_scan.containsKey(str_output_code)){//code duplicate -->del
                                map_output_scan.remove(str_output_code);
                                Set_View_Scan();

                            }else {
                                Check_Rank(str_output_code);
                            }
                        }else {
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Invalid QR code!")
                                    .show();
                        }
                    }
                }else if (data.trim().length() == 6){
                    Check_User(data.trim());

                }else {
                    new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Invalid QR code!")
                            .show();
                }
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

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

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

                if (str_role.trim().equals("LEADER")){
                    if (lot_out == true){
                        txt_leader_lotout.setText(data);
                    }else {
                        txt_leader.setText(data);
                    }
                }else {
                    txt_user.setText("");
                    MyAlert alert = new MyAlert(Classify_Output_Activity.this);
                    alert.setMessage("รหัสพนักงานนี้ไม่ใช่ leader!");
                    alert.show();
                }
            }else {
                if (Settings.getMap_user().get(data).getClassify().trim().equals("1")){
                    txt_user.setText(data);
                }else {
                    txt_user.setText("");
                    new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่อนุญาตให้ทำงานใน Classify")
                            .show();
                }
            }

        }else {
            txt_user.setText("");
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    private void Update_CLS_finish() {
            Block_button();

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

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

                String remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_classify_finish");
                json.put("output", txt_output.getText().toString().trim());
                json.put("remark", encode);
                json.put("classify_lot",str_cls_lot);
                json.put("user_id", txt_user.getText().toString());
                json.put("act_dt", dt_to_server);

                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/production_plan.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");
                            if (status.equals("success") && affected_rows > 0) {
                                Update_ClassifyLot();

                            } else {
                                Unblock_button();
                                new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                            layout_alert.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                Unblock_button();
                new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Update_ClassifyLot() {
        Block_button();

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

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

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

            String remark = edt_remark.getText().toString().trim();
            String encode = URLEncoder.encode(remark,"UTF-8");

            json.put("classify_lot",str_cls_lot);
            json.put("output", txt_output.getText().toString().trim());
            json.put("remark", encode);
            json.put("end_user_id", txt_user.getText().toString().trim());
            json.put("end_dt", dt_to_server);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/classify_lot.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) {
                           Insert_ClassifyOutput();

                        } else {
                            Unblock_button();
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't update ClassifyLot")
                                    .show();
                        }
                        layout_alert.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        Unblock_button();
                        new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            layout_alert.setVisibility(View.GONE);
            Unblock_button();
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_ClassifyOutput() {
        Block_button();

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

        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_output_scan.keySet()) {
                Output_Lists item = map_output_scan.get(key);

                String output_name = item.getOutput_name();
                String name = URLEncoder.encode(output_name,"UTF-8");

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("classify_lot", item.getClassify_lot());
                jsonParams.put("output_code", item.getOutput_code());
                jsonParams.put("output_name", name);
                jsonParams.put("output_type", item.getOutput_type());
                jsonParams.put("qty", item.getQty());
                jsonParams.put("nurse_call_user_id", item.getNurse_call_user_id());
                jsonParams.put("create_user_id", txt_user.getText().toString().trim());
                jsonParams.put("create_dt", dt_to_server);

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }
            json.put("cls_datas",jsonArray);
            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/classify_output.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) {
                            if (lot_out == true){
                                Update_LotOut();
                            }else {
                                Toast.makeText(Classify_Output_Activity.this, R.string.insert, Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        } else {
                            Unblock_button();
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert ClassifyOutput")
                                    .show();
                        }
                        layout_alert.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Update_LotOut() {
        Block_button();

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

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

                String remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

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

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("classify_lot", str_cls_lot);
                jsonParams.put("process", ProductionSchedule.PROCESS.CLASSIFY.toString());
                jsonParams.put("remark", encode);
                jsonParams.put("user_id", txt_leader_lotout.getText().toString().trim());
                jsonParams.put("act_dt", dt_to_server);

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);

                json.put("lotout_datas", jsonArray);

                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/production_plan.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");
                            if (status.equals("success") && affected_rows > 0) {

                                Toast.makeText(Classify_Output_Activity.this, R.string.insert, Toast.LENGTH_SHORT).show();
                                finish();

                            } else {
                                Unblock_button();
                                new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                            layout_alert.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                Unblock_button();
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Add_map_scan(String output_code, String output_name, String type,  String nurse_call) {
        Log.d(getString(R.string.tag), "Add_map_scan : " + output_code+"|"+nurse_call);
        int sum_output = 0, qty_input, sum, input_cls;

        //check qty
        for (String key : map_output_scan.keySet()) {
            Output_Lists output_lists = map_output_scan.get(key);
            String str_qty = output_lists.getQty();
            int int_qty = Integer.parseInt(str_qty);
            sum_output = (sum_output + int_qty);
        }
        String input = edt_qty.getText().toString().trim();
        qty_input = Integer.parseInt(input);
        input_cls = Integer.parseInt(str_input_cls);

        sum = (sum_output + qty_input);
        Log.d(getString(R.string.tag), "sum : " + sum +"="+sum_output+"+"+qty_input);

        if (sum > input_cls){
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่สามารถทำรายการได้ ผลรวมเกินจำนวน input ")
                    .show();
        }else {
            map_output_scan.put(output_code, new Output_Lists(
                    str_cls_lot,
                    output_code,
                    output_name,
                    type,
                    edt_qty.getText().toString().trim(),
                    nurse_call));

            Set_View_Scan();
            Log.d(getString(R.string.tag), "map_ng_scan: " + map_output_scan.size());
            txt_leader.setText("");
        }

        txt_scan_output.setText("");
        edt_qty.setText("");

    }

    private void Set_View_Scan() {
        //sum OK / NG
        sum_ng = 0; sum_ok = 0;

        for (String key : map_output_scan.keySet()){
            Output_Lists output_lists = map_output_scan.get(key);
            String type = output_lists.getOutput_type();

            if (type.trim().equals("OK")){
                Log.d(getString(R.string.tag), "sum OK: " + type);
                String qty_ok = output_lists.getQty();

                int_ok = Integer.parseInt(qty_ok);
                Log.d(getString(R.string.tag), "int_ok = " + int_ok);

                sum_ok = (sum_ok + int_ok);
                Log.d(getString(R.string.tag), "sum_ok" + sum_ok);

            }else{//NG
                Log.d(getString(R.string.tag), "sum NG: " + type);
                String qty_ng = output_lists.getQty();

                int_ng = Integer.parseInt(qty_ng);
                Log.d(getString(R.string.tag), "int_ng = " + int_ng);

                sum_ng = (sum_ng + int_ng);
                Log.d(getString(R.string.tag), "sum_ng" + sum_ng);

            }
        }
        txt_qty_ng.setText(String.valueOf(sum_ng));
        txt_output.setText(String.valueOf(sum_ok));

        list_ng.clear();
        for (String key : map_output_scan.keySet()){
            Output_Lists lists = map_output_scan.get(key);
            list_ng.add(new NG_Lists(
                    lists.getClassify_lot(),
                    lists.getOutput_code(),
                    lists.getOutput_name(),
                    lists.getQty(),
                    "CLASSIFY",
                    lists.getNurse_call_user_id(),
                    ""));
        }

        ng_adapter = new NG_Adapter(list_ng, Classify_Output_Activity.this,"CLASSIFY");
        view_cls_output.setAdapter(ng_adapter);
    }

    private void Cancel_NurseCall() {
        nurse_call = false;
        layout_cls_output.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);
        txt_scan_output.setText("");
        txt_leader.setText("");
    }

    private void OK_NurseCall() {
        nurse_call = false;
        layout_cls_output.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);

        str_leader = txt_leader.getText().toString().trim();
        str_output_code = txt_scan_output.getText().toString().trim();
        if (str_leader.equals("")){
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสleader!")
                    .show();
        }else {
            Get_OutputCode list = map_code_ng.get(str_output_code);
            String name = list.getName();

            Add_map_scan(str_output_code, name,"NG", str_leader);
        }
    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_rank");
            json.put("box", output_code);
            json.put("ics", str_ics);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/classify_rank.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){
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Classify Rank not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                str_cls_rank = jArray.getJSONObject(i).getString("BOX").trim() == "null" ? "" : jArray.getJSONObject(i).getString("BOX").trim();;
                            }
                            Log.d(getString(R.string.tag), "str_cls_rank: " + str_cls_rank);
                            if (str_cls_rank.trim().equals("")){
                                new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Classify Rank not found!")
                                        .show();
                            }else {
                                Add_map_scan(output_code, str_cls_rank,"OK", "");
                            }
                        }
                        layout_alert.setVisibility(View.GONE);
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Classify_Output_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){
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("NG code not found!")
                                    .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){
                                    new SweetAlertDialog(Classify_Output_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(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_classify_lot");
            json.put("classify_lot", str_cls_lot);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/classify_lot.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){
                            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Classify lot not found!")
                                    .show();
                        }else {
                                for (int i = 0; i < jArray.length(); i++) {
                                    str_input_cls = jArray.getJSONObject(i).getString("input").trim();
                                }
                              txt_input.setText(str_input_cls);
                            Log.d(getString(R.string.tag), "Classify str_input_cls : " + str_input_cls);
                        }
                        layout_alert.setVisibility(View.GONE);
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

//    private void Check_User(String user_id) {
//        try {
//            layout_alert.setVisibility(View.VISIBLE);
//            txt_message.setText("Please wait, searching data...");
//
//            JSONObject json = new JSONObject();
//            json.put("cmd", "search");
//            json.put("user_id", user_id);
//
//            new AsyncHttpClient(getApplicationContext(),
//                    Settings.getMgmtList().get("web_api")+ "/users.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(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("User ID not found!")
//                                    .show();
//                        }else {
//                            if (nurse_call == true || lot_out == true){//scan leader
//                                for (int i = 0; i < jArray.length(); i++) {
//                                    str_role = jArray.getJSONObject(i).getString("Role").trim();
//                                }
//                                if (str_role.trim().equals("LEADER")){
//                                    if (lot_out == true){
//                                        txt_leader_lotout.setText(user_id);
//                                    }else {
//                                        txt_leader.setText(user_id);
//                                    }
//                                    layout_alert.setVisibility(View.GONE);
//                                }else {
//                                    layout_alert.setVisibility(View.GONE);
//                                    new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                            .setTitleText("WARNING")
//                                            .setContentText("User isn't leader!")
//                                            .show();
//                                }
//                            }else {
//                                layout_alert.setVisibility(View.GONE);
//                                txt_user.setText(user_id);
//                            }
//                        }
//                    }catch (JSONException e) {
//                        layout_alert.setVisibility(View.GONE);
//                        new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                                .setTitleText("ERROR")
//                                .setContentText(e.getMessage())
//                                .show();
//                    }
//                }
//            }.execute();
//        }catch (JSONException e) {
//            layout_alert.setVisibility(View.GONE);
//            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                    .setTitleText("ERROR")
//                    .setContentText(e.getMessage())
//                    .show();
//        }
//    }

    private void Return_Layout() {
        scanner = true;
        confirm = false;
        layout_btn_finish.setVisibility(View.VISIBLE);
        layout_scan_output.setVisibility(View.VISIBLE);
        layout_btn_confirm.setVisibility(View.GONE);
        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);
        layout_remark.setBackgroundResource(R.drawable.button_backgroup_menu);
        edt_remark.setEnabled(true);
    }

    private void Set_layout_View() {
        if (map_output_scan.size() == 0 ||
                txt_user.getText().toString().equals("")){
            new SweetAlertDialog(Classify_Output_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information!")
                    .show();
        }else {
            scanner = false;
            confirm = true;
            layout_btn_finish.setVisibility(View.GONE);
            layout_scan_output.setVisibility(View.GONE);
            layout_btn_confirm.setVisibility(View.VISIBLE);
            txt_user.setBackgroundResource(R.drawable.img_backgroup);
            layout_remark.setBackgroundResource(R.drawable.img_backgroup);
            edt_remark.setEnabled(false);
        }
    }


    @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:
                    if (confirm == true){
                        Return_Layout();
                    }else {
                        Intent intent = new Intent(Classify_Output_Activity.this, Search_ProcessSheet_Lot_Activity.class);
                        startActivity(intent);
                        finish();
                    }
                    break;
                case P2:
                    if (lot_out == true){
                        if (b_confirm == true) {
                            Block_button();
                            Update_Output();
                        }

                    } else if (nurse_call == true) {
                        OK_NurseCall();

                    }else if (confirm == true){
                        if (b_confirm == true) {
                            Block_button();
                            Check_Output();
                        }
                    }else {
                        Set_layout_View();
                    }
                    break;

                case P3:
                    if (lot_out == true){
                        Cancel_LotOut();

                    }else if (nurse_call == true){
                        Cancel_NurseCall();
                    }else {
                        Clear_Output();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}