package com.tomas.st_nset;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.st_nset.List_Class.ItemMaster_item;
import com.tomas.st_nset.List_Class.Location_item;
import com.tomas.st_nset.List_Class.Stocktaking_item;
import com.tomas.st_nset.lib.KeyMapping;
import com.tomas.st_nset.lib.MyAlert;
import com.tomas.st_nset.lib.Scanner;
import com.tomas.st_nset.lib.Settings;
import com.tomas.st_nset.lib.common.AsyncHttpClient;
import com.tomas.st_nset.lib.common.Utils;

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

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

import cn.pedant.SweetAlert.SweetAlertDialog;

public class StocktakingActivity extends Scanner implements View.OnClickListener {
    Bundle bundle;
    String str_main, str_month, str_slip_type, str_process, str_date, str_slip_no, str_qty_slip, str_location_slip, str_wsh_cd,
            str_item_no, str_item_name, str_inv_wip_type, datetime_to_server, CANCEL_FLAG, COUNT_TM, DOC_STATUS, CHG_PGM,
            str_previous_qty, Result, str_previous_result, ITEM_CTR_CD, slip_HEADER, slip_LAST, slip_COUNT, slip_MONTH_YEAR,
            COUNT_TM_LAST, SLIP_NUMBER, Duplicate_lo, str_slip_datetime, Key_map, PRE_COUNT_TM, str_location_mode, str_item_umsr, USER_ID,
            str_count_job, str_wip_slip_type;

    String[] tokens;
    TextView txt_header, txt_mode, txt_itemname, txt_qty, txt_scan, txt_status, txt_result,txt_itemcode, txt_message_alert, txt_unit, txt_work_count;
    EditText edt_date, edt_location, edt_qty, edt_itemcode;
    Button btn_clear, btn_add, btn_confirm;
    Spinner spinner_result;
    LinearLayout layout_scan, layout_work_count;
    MyAlert myAlertDialog;
    ConstraintLayout layout_alert;
    DecimalFormat decimalFormat,decimal_format2;
    boolean b_confirm;

    Map<String, Location_item> item_location;
    Map<String,ItemMaster_item> list_items;
    ArrayList<String> arrayList;
    Map<String, Stocktaking_item> mapItems;
    Calendar calendar;
    SimpleDateFormat format_dt, format_dt_server;
    Dialog dialog;
    boolean Overwrite, Scan_location, Add_Manual;
    float sum_previous_qty, f_total, last_qty, sum_total;
    int slip_LAST_int, slip_COUNT_int, int_run_slip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stocktaking);
        myAlertDialog = new MyAlert(this);

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

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

        decimalFormat = new DecimalFormat("#,##0.00");
        decimal_format2 = new DecimalFormat("##0.00");
        item_location = new LinkedHashMap<>();
        list_items = new LinkedHashMap<>();
        arrayList=new ArrayList<>();

        mapItems = new LinkedHashMap<>();
        mapItems.clear();

        b_confirm = true;
        Overwrite = false;
        Scan_location = false;
        Add_Manual = false;
        int_run_slip = 0;
        sum_previous_qty = 0;
        CHG_PGM = "HDTINV_TAKING";
        DOC_STATUS = "";
        CANCEL_FLAG = "";
        Result = "";

        bundle = getIntent().getExtras();
        str_main = bundle.getString("main");
        str_month = bundle.getString("month");
        str_slip_type = bundle.getString("slip_type");
        str_process = bundle.getString("process");

        edt_itemcode = (EditText)findViewById(R.id.edt_itemcode);
        txt_itemcode = (TextView)findViewById(R.id.txt_itemcode);
        txt_work_count = (TextView)findViewById(R.id.txt_work_count);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_clear = (Button) findViewById(R.id.btn_clear);
        txt_result = (TextView)findViewById(R.id.txt_result);
        spinner_result = (Spinner) findViewById(R.id.spinner_result);
        String[] process = getResources().getStringArray(R.array.Result);
        ArrayAdapter<String> adapterProcess = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, process);
        spinner_result.setAdapter(adapterProcess);
        layout_scan = (LinearLayout) findViewById(R.id.layout_scan);
        layout_work_count = (LinearLayout) findViewById(R.id.layout_work_count);

        if (str_main.equals("Stocktaking")){
            String[] tokens = str_process.split("-", -1);
            str_process = tokens[1];
            if (str_process.trim().equals("1st")){
                COUNT_TM = "1";
            }else if (str_process.trim().equals("2nd")){
                COUNT_TM = "2";
            }else {
                COUNT_TM = "3";
            }
        }else {//Sampling
            layout_scan.setVisibility(View.GONE);
            layout_work_count.setVisibility(View.VISIBLE);
            edt_itemcode.setVisibility(View.GONE);
            txt_itemcode.setVisibility(View.VISIBLE);

            txt_result.setVisibility(View.GONE);
            spinner_result.setVisibility(View.VISIBLE);

            btn_clear.setVisibility(View.GONE);
            btn_add.setVisibility(View.GONE);

            if (str_process.trim().equals("Sampling")){
                COUNT_TM = "4";
            }else {
                COUNT_TM = "5";
            }

            Count_Job();
        }

        if (str_slip_type.equals("Raw material")){
            str_inv_wip_type = "1";
            str_slip_type = "RM";
            ITEM_CTR_CD = "RM-TK";

        }else if (str_slip_type.equals("Finish good")){
            str_inv_wip_type = "2";
            str_slip_type = "FG";
            ITEM_CTR_CD = "FG-TK";

//        }else if (str_slip_type.equals("WIP SFG")){
//            str_inv_wip_type = "3";
//            str_slip_type = "WIP SFG";
//            ITEM_CTR_CD = "WI-TK";

        }else {
//            str_inv_wip_type = "4";
//            str_slip_type = "WIP RM";
            str_inv_wip_type = "3";
            str_slip_type = "WIP";
            ITEM_CTR_CD = "WI-TK";
        }

        Log.d(getString(R.string.tag), str_main + " " + str_month+ " " +str_slip_type+ " " +str_process+"/"+COUNT_TM);

        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_header.setText(str_main);

        txt_mode = (TextView) findViewById(R.id.txt_mode);
        txt_mode.setText(str_slip_type+" "+str_process);

        edt_date = (EditText)findViewById(R.id.edt_date);
        calendar = Calendar.getInstance();
        format_dt = new SimpleDateFormat("dd/MM/yyyy");
        format_dt_server = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        str_date = format_dt.format(calendar.getTime());
        edt_date.setText(str_date);
        edt_date.setInputType(InputType.TYPE_NULL);
        edt_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(StocktakingActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date = (String.format("%2s",dayOfMonth).replace(' ','0'))+"/"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0')+"/"+ year);
                        edt_date.setText(str_date);

                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        txt_itemname = (TextView)findViewById(R.id.txt_itemname);
        txt_qty = (TextView)findViewById(R.id.txt_total);
        txt_unit =(TextView)findViewById(R.id.txt_unit);
        txt_scan = (TextView)findViewById(R.id.txt_scan);
        txt_status = (TextView)findViewById(R.id.txt_status);
        edt_location = (EditText)findViewById(R.id.edt_location);
        edt_qty = (EditText)findViewById(R.id.edt_qty);

        txt_itemcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Alert_Dialog_KeyItem();

            }
        });

    }

    private void Alert_Dialog_KeyItem() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_key_itemcode, null);
        builder.setView(view);
        builder.setCancelable(false);

        EditText Message = (EditText) view.findViewById(R.id.edit_text);
        Button btn_enter = (Button)view.findViewById(R.id.btn_enter);
        Button btn_alert_cancel = (Button)view.findViewById(R.id.btn_cancel);
        final AlertDialog ad = builder.show();

        btn_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = Message.getText().toString().trim();
                if (msg.trim().equals("")){
                    myAlertDialog.setMessage("Please enter item code");
                    myAlertDialog.setTypeAlert(false);
                    myAlertDialog.show();

                }else{
                    if (edt_location.getText().toString().trim().equals("")){
                        myAlertDialog.setMessage("Please enter location");
                        myAlertDialog.setTypeAlert(false);
                        myAlertDialog.show();
                        ad.dismiss();
                    }else {
                        txt_itemcode.setText(msg);
                        Check_ItemMaster(msg);
                        ad.dismiss();
                    }
                }
            }
        });

        btn_alert_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        try {
            Log.d(getString(R.string.tag), "data read:" + data);
            tokens = data.split(",");
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 1){//location
                if (mapItems.size() > 0)
                    return;

                edt_location.setText(data.trim());
                Scan_location = true;
                Check_Mode_location();

            }else{//
                if (edt_location.getText().toString().trim().equals("")){
                    myAlertDialog.setMessage("Please enter location");
                    myAlertDialog.setTypeAlert(false);
                    myAlertDialog.show();
                }else {
                    if (Scan_location == false){//Manual location
                        Check_location("processData",tokens, "");

                    }else {//Scan location

                        Check_SlipType(tokens);
                    }
                }
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*processData*")
                    .show();
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Count_Job() {
        Log.d(getString(R.string.tag), "Count_Job:");
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "count_job_user");
            json.put("MONTH_YEAR",str_month);
            json.put("USER_ID",Settings.getLoginUser().getId());

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

                            for (int i = 0; i < jArray.length(); i++) {
                                str_count_job = jArray.getJSONObject(i).getString("count_job");
                            }

                            txt_work_count.setText(str_count_job);
                        layout_alert.setVisibility(View.GONE);

                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Count_Job*")
                                .show();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Count_Job*")
                    .show();
        }
    }

    private void Check_Mode_location() {
        Log.d(getString(R.string.tag), "Check_Mode_location:");
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "query");
            json.put("LOCATION", edt_location.getText().toString().trim());

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_location_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){
                            myAlertDialog.setMessage("Location not found");
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            Scan_location = false;
                            layout_alert.setVisibility(View.GONE);
                        }else {

                            for (int i = 0; i < jArray.length(); i++) {
                                str_location_mode = jArray.getJSONObject(i).getString("MODE");
                            }

                            if (!str_location_mode.trim().equals(str_slip_type)){
                                myAlertDialog.setMessage("Location doesn't match mode");
                                myAlertDialog.setTypeAlert(false);
                                myAlertDialog.show();
                                Scan_location = false;
                                edt_location.setText("");
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Check_Mode_location*")
                                .show();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Check_Mode_location*")
                    .show();
        }
    }

    private void Check_location(String mode, String[] Tokens, String item) {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");

        Log.d(getString(R.string.tag), "Mode:" + mode);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "query");
            json.put("LOCATION", edt_location.getText().toString().trim());

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_location_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){
                            myAlertDialog.setMessage("Location not found");
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                str_location_mode = jArray.getJSONObject(i).getString("MODE");
                            }

                            if (!str_location_mode.trim().equals(str_slip_type)){
                                myAlertDialog.setMessage("Location doesn't match mode");
                                myAlertDialog.setTypeAlert(false);
                                myAlertDialog.show();

                                edt_location.setText("");
                            }else {

                                if (mode.equals("Add_qty")) {
                                    Check_ItemMaster(item);
                                } else {
                                    Check_SlipType(Tokens);
                                }
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Check_location*")
                                .show();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Check_location*")
                    .show();
        }
    }


    private void Check_SlipType(String[] tokens) {
        Key_map = "";
        if (tokens[0].trim().equals("M")) {
//            str_slip_type = "M(Manual)";
            edt_itemcode.setText(tokens[1]);

            if (str_main.trim().equals("Sampling")) {
                Check_ItemMaster(tokens[1]);
            }

        }else {
//            if (str_slip_type.equals("RM") || str_slip_type.equals("WIP RM")) {
            if (str_slip_type.equals("RM")) {
                Log.d(getString(R.string.tag), "RM" + tokens[0]);
                if (tokens[0].contains("RN") || tokens[0].contains("RP") || tokens[0].contains("RT")) {//check slip type RM
                    str_item_no = tokens[1];
                    str_wsh_cd = tokens[2];
                    str_location_slip = tokens[3];
                    str_qty_slip = tokens[5];
                    str_slip_no = tokens[8];
                    str_slip_datetime = tokens[13];

                    str_slip_datetime = str_slip_datetime.replace("/", "-");

                    Key_map = str_slip_no + " " + str_slip_datetime;

                    Log.d(getString(R.string.tag), "RM :" + str_item_no + "|" + str_wsh_cd + "|" + str_location_slip + "|" + str_qty_slip +
                            "|" + str_slip_no + "|" + str_item_name + "|" + str_slip_datetime + "|" + Key_map);


                    if (str_main.trim().equals("Stocktaking")) {
                        Check_MapItem();
                    } else {
                        Check_ItemMaster(str_item_no);
                    }

                } else {
                    myAlertDialog.setMessage("Slip type is not correct");
                    myAlertDialog.setTypeAlert(false);
                    myAlertDialog.show();
                }

            } else if (str_slip_type.equals("FG")) {
                Log.d(getString(R.string.tag), "FG" + tokens[0]);
                if (tokens[0].equals("FG")) {
                    str_item_no = tokens[3].substring(2);
                    str_wsh_cd = "";
                    str_location_slip = "";
                    str_qty_slip = tokens[8];
                    str_slip_no = tokens[1];

                    str_slip_datetime = tokens[11] + " " + tokens[12];
                    str_slip_datetime = str_slip_datetime.replace("/", "-");

                    Key_map = str_slip_no + " " + str_slip_datetime;

                    Log.d(getString(R.string.tag), "FG :" + str_item_no + "|" + str_wsh_cd + "|" + str_location_slip + "|" + str_qty_slip +
                            "|" + str_slip_no + "|" + str_item_name + "|" + str_slip_datetime + "|" + Key_map);

                    if (str_main.trim().equals("Stocktaking")) {
                        Check_MapItem();
                    } else {
                        Check_ItemMaster(str_item_no);

                    }

                } else {
                    myAlertDialog.setMessage("Slip type is not correct");
                    myAlertDialog.setTypeAlert(false);
                    myAlertDialog.show();
                }

            } else if (str_slip_type.equals("WIP")) {
                str_wip_slip_type = "WIP_OTHER";
                Log.d(getString(R.string.tag), "WIP SFG" + tokens[0]);
                if (tokens[0].equals("SM")) {
                    str_item_no = tokens[3];
                    str_wsh_cd = "";
                    str_location_slip = "";
                    str_qty_slip = tokens[8];
                    str_slip_no = tokens[1];

                    str_slip_datetime = tokens[11] + " " + tokens[12];
                    str_slip_datetime = str_slip_datetime.replace("/", "-");

                    Key_map = str_slip_no + " " + str_slip_datetime;

                    Log.d(getString(R.string.tag), "WIP SFG :" + str_item_no + "|" + str_wsh_cd + "|" + str_location_slip + "|" + str_qty_slip +
                            "|" + str_slip_no + "|" + str_item_name + "|" + str_slip_datetime + "|" + Key_map);

                    if (str_main.trim().equals("Stocktaking")) {
                        Check_MapItem();

                    } else {
                        Check_ItemMaster(str_item_no);

                    }

                } else if (tokens[0].substring(0, 1).equals("W")) {
                    str_item_no = tokens[4];
                    str_wsh_cd = "";
                    str_location_slip = "";
                    str_qty_slip = tokens[7];
                    str_slip_no = tokens[0];

                    str_slip_datetime = tokens[9] + " " + tokens[10];
                    str_slip_datetime = str_slip_datetime.replace("/", "-");

                    Key_map = str_slip_no + " " + str_slip_datetime;

                    Log.d(getString(R.string.tag), "WIP SFG :" + str_item_no + "|" + str_wsh_cd + "|" + str_location_slip + "|" + str_qty_slip +
                            "|" + str_slip_no + "|" + str_item_name + "|" + str_slip_datetime + "|" + Key_map);

                    if (str_main.trim().equals("Stocktaking")) {
                        Check_MapItem();
                    } else {
                        Check_ItemMaster(str_item_no);

                    }
                } else if (tokens[0].equals("NG")) {
                    str_item_no = tokens[3];
                    str_wsh_cd = "";
                    str_location_slip = "";
                    str_qty_slip = tokens[8];
                    str_slip_no = tokens[1];

                    str_slip_datetime = tokens[11] + " " + tokens[12];
                    str_slip_datetime = str_slip_datetime.replace("/", "-");

                    Key_map = str_slip_no + " " + str_slip_datetime;

                    Log.d(getString(R.string.tag), "WIP SFG :" + str_item_no + "|" + str_wsh_cd + "|" + str_location_slip + "|" + str_qty_slip +
                            "|" + str_slip_no + "|" + str_item_name + "|" + str_slip_datetime + "|" + Key_map);

                    if (str_main.trim().equals("Stocktaking")) {
                        Check_MapItem();
                    } else {
                        Check_ItemMaster(str_item_no);

                    }

                } else if (tokens[0].contains("RN") || tokens[0].contains("RP") || tokens[0].contains("RT")) {//check slip type RM
                    str_wip_slip_type = "WIP_R";
                    str_item_no = tokens[1];
                    str_wsh_cd = tokens[2];
                    str_location_slip = tokens[3];
                    str_qty_slip = tokens[5];
                    str_slip_no = tokens[8];
                    str_slip_datetime = tokens[13];
//
                    str_slip_datetime = str_slip_datetime.replace("/", "-");
//
//                    Key_map = str_slip_no + " " + str_slip_datetime;
//
//                    Log.d(getString(R.string.tag), "WIP RM :" + str_item_no + "|" + str_wsh_cd + "|" + str_location_slip + "|" + str_qty_slip +
//                            "|" + str_slip_no + "|" + str_item_name + "|" + str_slip_datetime + "|" + Key_map);
//
//
                    if (str_main.trim().equals("Stocktaking")) {
//                        Check_MapItem();
                        edt_itemcode.setText(str_item_no);
                    } else {
                        Check_ItemMaster(str_item_no);
                    }

                } else {
                    myAlertDialog.setMessage("Slip type is not correct");
                    myAlertDialog.setTypeAlert(false);
                    myAlertDialog.show();
                }
            }
        }
    }

    private void Check_MapItem() {
        Log.d(getString(R.string.tag), "mapItems " + String.valueOf(mapItems.size()));
        if (mapItems.size() == 0) {
            //check item master
            Check_ItemMaster(str_item_no);

        } else {
            if (edt_itemcode.getText().toString().trim().equals(str_item_no)){//Check item code match
                Log.d(getString(R.string.tag), "item code match : " + str_item_no);


                Log.d(getString(R.string.tag), "item Key_map : " + Key_map);

                if (mapItems.containsKey(Key_map)) {//contain slip RN.No
                    myAlertDialog.setMessage("It's a duplicate");
                    myAlertDialog.setTypeAlert(false);
                    myAlertDialog.show();

                } else {
                    Check_Duplicate(str_slip_no,str_slip_datetime);
                }

            }else{
                myAlertDialog.setMessage("Item code not match");
                myAlertDialog.setTypeAlert(false);
                myAlertDialog.show();

            }
        }
    }

    private void Check_ItemMaster(String item_no) {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "query");
            json.put("id", item_no);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/item_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){
                            myAlertDialog.setMessage("Item code not found");
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);

                            Clear_itemcode();

                        }else {

                            for (int i = 0; i < jArray.length(); i++) {
                                str_item_no = jArray.getJSONObject(i).getString("ITEM_NO");
                                str_item_name = jArray.getJSONObject(i).getString("ITEM_DESC");
                                str_item_umsr = jArray.getJSONObject(i).getString("ITEM_UMSR").trim()=="null"?"":jArray.getJSONObject(i).getString("ITEM_UMSR").trim();
                            }

                            edt_itemcode.setText(str_item_no);
                            txt_itemname.setText(str_item_name);
                            txt_itemcode.setText(str_item_no);
                            txt_unit.setText(str_item_umsr);

                            Log.d(getString(R.string.tag), str_main +" / "+ String.valueOf(Add_Manual));

                            if (str_main.trim().equals("Stocktaking") && Add_Manual == false){
                                Log.d(getString(R.string.tag), "if");
                                Check_Duplicate(str_slip_no, str_slip_datetime);

                            }else{
                                Log.d(getString(R.string.tag), "else");
                                Check_LastStocktaking();
                            }
                        }
                    } catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Check_ItemMaster*")
                                .show();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Check_ItemMaster*")
                    .show();
        }
    }

    private void Check_Duplicate(String slip_no, String slip_dt) {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");

        try {
            JSONObject json = new JSONObject();

            if (str_slip_type.trim().equals("FG")) {
                json.put("cmd", "check_duplicate");
                json.put("MONTH_YEAR", str_month);
                json.put("LOCATION", edt_location.getText().toString().trim());
                json.put("COUNT_TM", COUNT_TM);
                json.put("SLIP_NO", slip_no);
                json.put("LABELPRINT_DATE", slip_dt);

            }else if (str_slip_type.trim().equals("RM")){
                json.put("cmd", "check_duplicate_R");
                json.put("MONTH_YEAR", str_month);
                json.put("LOCATION", edt_location.getText().toString().trim());
                json.put("COUNT_TM", COUNT_TM);
                json.put("SLIP_NO", slip_no);
                json.put("INV_WIP_TYPE", str_inv_wip_type);
                json.put("LABELPRINT_DATE", slip_dt);

            }else {//WIP
                if (str_wip_slip_type.trim().equals("WIP_R")) {//RN RP RT
                    json.put("cmd", "check_duplicate_R");
                    json.put("MONTH_YEAR", str_month);
                    json.put("LOCATION", edt_location.getText().toString().trim());
                    json.put("COUNT_TM", COUNT_TM);
                    json.put("SLIP_NO", slip_no);
                    json.put("INV_WIP_TYPE", str_inv_wip_type);
                    json.put("LABELPRINT_DATE", slip_dt);

                }else {
                    json.put("cmd", "check_duplicate");
                    json.put("MONTH_YEAR", str_month);
                    json.put("LOCATION", edt_location.getText().toString().trim());
                    json.put("COUNT_TM", COUNT_TM);
                    json.put("SLIP_NO", slip_no);
                    json.put("LABELPRINT_DATE", slip_dt);
                }
            }

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

                            if (mapItems.size() == 0){

                                Check_LastStocktaking();
                            }else {
                                AddToMapItem();

                                Log.d(getString(R.string.tag), "KEY = " + Key_map);
                                mapItems.put(Key_map.trim(), new Stocktaking_item(
                                        str_month,
                                        str_inv_wip_type,
                                        str_slip_no,
                                        str_wsh_cd,
                                        "",
                                        str_location_slip,
                                        str_item_no,
                                        str_item_name,
                                        str_qty_slip,
                                        str_slip_datetime));

                                txt_scan.setText(String.valueOf(mapItems.size()));
                                calculate_total();

                                Log.d(getString(R.string.tag), "2mapItems " + String.valueOf(mapItems.size()));
                            }

                        }else {
                            for(int i=0;i<jArray.length();i++) {
                                Duplicate_lo  = jArray.getJSONObject(i).getString("LOCATION");
                            }

                            myAlertDialog.setMessage("It's a duplicate \n"+"in location "+Duplicate_lo);
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);


                            if (mapItems.size() == 0){
                                Clear_itemcode();
                            }
                        }
                        layout_alert.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Check_Duplicate*")
                                .show();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Check_Duplicate*")
                    .show();
        }
    }


    private void Check_LastStocktaking() {
        mapItems.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "check_last_stocktaking");
            json.put("MONTH_YEAR", str_month);
            json.put("LOCATION", edt_location.getText().toString().trim());
            json.put("ITEM_NO", edt_itemcode.getText().toString().trim());

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_stocktaking.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 (str_main.trim().equals("Stocktaking")) {
                            if (jArray.length() == 0){//ยังไม่ได้นับครั้งที่1
                                //เลือกนับครั้งที่1
                                if (COUNT_TM.trim().equals("1")){
                                    if (Add_Manual == true) {
                                        Gen_SlipNo();
                                    } else {
                                        AddToMapItem();
                                    }
                                   Log.d(getString(R.string.tag), "2mapItems " + String.valueOf(mapItems.size()));

                                }else{//เลือกครั้งที่ 2 3 จะยังนับไม่ได้ เพราะยังไม่ได้นับครั้งที่1
                                    myAlertDialog.setMessage("1ST No Data");
                                    myAlertDialog.setTypeAlert(false);
                                    myAlertDialog.show();
                                    layout_alert.setVisibility(View.GONE);

                                    Clear_itemcode();
                                }
                            }else{//ครั้งล่าสุด ว่านับครั้งที่เท่าไหร่
                                last_qty = 0;
                                float qty;
                                for (int i = 0; i < jArray.length(); i++) {
                                    COUNT_TM_LAST = jArray.getJSONObject(i).getString("COUNT_TM");
                                    str_previous_qty = jArray.getJSONObject(i).getString("QUANTITY");
                                    str_previous_result = jArray.getJSONObject(i).getString("DOC_STATUS");
                                    qty = Float.parseFloat(str_previous_qty);

                                    last_qty = (last_qty + qty);
                                }
                                Log.d(getString(R.string.tag), "str_previous_result: " + str_previous_result);
                                Log.d(getString(R.string.tag), "last_qty: " + String.valueOf(last_qty));

//                                //result DOC_STATUS
                                if (str_previous_result.trim().equals("1")) {
                                    txt_result.setText("Matching");
                                    txt_result.setBackgroundResource(R.color.green);
                                } else if (str_previous_result.trim().equals("2")) {
                                    spinner_result.setSelection(1);
                                    txt_result.setText("Unmatching");
                                    txt_result.setBackgroundResource(R.color.red);
                                }
                                txt_result.setTextColor(Color.parseColor("#FFFFFF"));

                                txt_status.setTextColor(Color.parseColor("#FFFFFF"));
                                txt_status.setBackgroundResource(R.color.green);

                                if (COUNT_TM_LAST.trim().equals("1")){//ล่าสุดนับ1 จะนับ3ไม่ได้ นับ 1 กับ 2ได้
                                    txt_status.setText("1ST END");

                                    if (COUNT_TM.trim().equals("3")){
                                        myAlertDialog.setMessage("2ND No Data");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();

                                    }else {//ถ้าเลือกนับ 1 กับ 2
                                        PRE_COUNT_TM = "1";
                                        if (Add_Manual == true) {
                                            Gen_SlipNo();
                                        } else {
                                            AddToMapItem();
                                        }
                                    }
                                }else if (COUNT_TM_LAST.trim().equals("2")){
                                    //ครั้งล่าสุดเป็น 2 ก็สามารถ สแกนครั้ง 2 3 เพิ่มได้
                                    txt_status.setText("2ND END");

                                    if (COUNT_TM.trim().equals("1")) {
                                        myAlertDialog.setMessage("Stocktaking 2RD");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();
                                    }else if (COUNT_TM.trim().equals("2")){
//                                        query ข้อมูล 1 มาเทียบ แล้วเอา 2 มาคำนวนรวมกับscanครั้งใหม่
                                        PRE_COUNT_TM = "1";
                                        Sum_PreviousData(PRE_COUNT_TM);

                                    }else{// COUNT_TM == 3
                                        PRE_COUNT_TM = "2";
                                        if (Add_Manual == true) {
                                            Gen_SlipNo();
                                        } else {
                                            AddToMapItem();
                                        }
                                    }

                                }else if (COUNT_TM_LAST.trim().equals("3")){
                                    txt_status.setText("3RD END");

                                    if (COUNT_TM.trim().equals("3")) {
                                        //ต้องไปเอาข้อมูล 2 มาเทียบ แล้วเอา 3 มาคำนวนรวมกับscanครั้งใหม่
                                        PRE_COUNT_TM = "2";
                                        Sum_PreviousData(PRE_COUNT_TM);

                                    }else {//จะไม่นับ 1 2 เพิ่ม
                                        myAlertDialog.setMessage("Stocktaking 3RD");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();
                                    }

                                }else if (COUNT_TM_LAST.trim().equals("4")){
                                    //จะ COUNT_TM_LAST.trim().equals("4")ได้ ต้องนับ 1,2 ก่อน
                                    if (str_previous_result.trim().equals("1")) {//Matching
                                        myAlertDialog.setMessage("Sample END data matching");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();
                                    } else {//Unmatching
                                      //เช็คว่ามีการนับครั้งที่ 3 รึยัง ถ้ายังไม่ได้นับ นับได้ เดิมนับไม่ได้
                                        if (COUNT_TM.trim().equals("3")) {
                                            Check_COUNT_TM3();
                                        }else{
                                            txt_status.setText("2ND END");
                                        }
                                    }
                                }else{
                                    //จะ COUNT_TM_LAST.trim().equals("5")ได้ ต้องนับ 1,2 ก่อน
                                    if (str_previous_result.trim().equals("1")) {//Matching
                                        myAlertDialog.setMessage("RE-Sample END data matching");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();
                                    } else {//Unmatching
                                        //เช็คว่ามีการนับครั้งที่ 3 รึยัง ถ้ายังไม่ได้นับ นับได้ เดิมนับไม่ได้
                                        if (COUNT_TM.trim().equals("3")) {
                                            Check_COUNT_TM3();
                                        }else{
                                            txt_status.setText("2ND END");
                                        }
                                    }
                                }
                            }
                        }else {//sampling
                            if (jArray.length() == 0) {
                                myAlertDialog.setMessage("No Data Stocktaking");
                                myAlertDialog.setTypeAlert(false);
                                myAlertDialog.show();
                                layout_alert.setVisibility(View.GONE);

                                Clear_itemcode();

                            } else {
                                for (int i = 0; i < jArray.length(); i++) {
                                    String Key = jArray.getJSONObject(i).getString("SLIP_NO") + " " + jArray.getJSONObject(i).getString("LABELPRINT_DATE");
                                    mapItems.put(Key.trim()
                                            , new Stocktaking_item(
                                                    jArray.getJSONObject(i).getString("MONTH_YEAR"),
                                                    jArray.getJSONObject(i).getString("INV_WIP_TYPE"),
                                                    jArray.getJSONObject(i).getString("SLIP_NO"),
                                                    jArray.getJSONObject(i).getString("WHS_CD"),
                                                    jArray.getJSONObject(i).getString("WS_CD"),
                                                    jArray.getJSONObject(i).getString("LOCATION"),
                                                    jArray.getJSONObject(i).getString("ITEM_NO"),
                                                    str_item_name,
                                                    jArray.getJSONObject(i).getString("QUANTITY"),
                                                    jArray.getJSONObject(i).getString("LABELPRINT_DATE")));

                                    COUNT_TM_LAST = jArray.getJSONObject(i).getString("COUNT_TM");
                                    str_previous_qty = jArray.getJSONObject(i).getString("QUANTITY");
                                    str_previous_result = jArray.getJSONObject(i).getString("DOC_STATUS");
                                    CANCEL_FLAG = jArray.getJSONObject(i).getString("CANCEL_FLAG");
                                    USER_ID = jArray.getJSONObject(i).getString("USER_ID");
                                }

                                Overwrite = false;
                                if (COUNT_TM.trim().equals("4")){//sample
                                    if (COUNT_TM_LAST.trim().equals("1")) {
                                        myAlertDialog.setMessage("1ST END It can't sampling");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();

                                    }else if (COUNT_TM_LAST.trim().equals("5")) {
                                        myAlertDialog.setMessage("Re-Sample END");
                                        myAlertDialog.setTypeAlert(false);
                                        myAlertDialog.show();
                                        layout_alert.setVisibility(View.GONE);

                                        Clear_itemcode();

                                    }else if (COUNT_TM_LAST.trim().equals("4")){  //sample แล้ว 1 ครั้ง

                                        myAlertDialog.setMessage("Sample by "+USER_ID);
                                            myAlertDialog.setTypeAlert(false);
                                            myAlertDialog.show();
                                            layout_alert.setVisibility(View.GONE);
                                        Clear_itemcode();

//                                        if (CANCEL_FLAG.trim().equals("2")) {
//                                            myAlertDialog.setMessage("It has been overwritten,  \n" +
//                                                    "so it cannot be updated");
//                                            myAlertDialog.setTypeAlert(false);
//                                            myAlertDialog.show();
//                                            layout_alert.setVisibility(View.GONE);
//
//                                            Clear_itemcode();
//
//                                        }else {
//                                            Overwrite = true;
//                                            txt_status.setText("Sample END");
//
//                                            Set_sample_layout();
//                                        }

                                    }else {
                                        if (COUNT_TM_LAST.trim().equals("2")) {
                                            txt_status.setText("2ND END");

                                        } else if (COUNT_TM_LAST.trim().equals("3")) {
                                            txt_status.setText("3RD END");

                                        }

                                        Set_sample_layout();
                                    }

                                }else {// re-sample COUNT_TM == 5
                                   if (COUNT_TM_LAST.trim().equals("5")){
                                       myAlertDialog.setMessage("Sample by "+USER_ID);
                                       myAlertDialog.setTypeAlert(false);
                                       myAlertDialog.show();
                                       layout_alert.setVisibility(View.GONE);
                                       Clear_itemcode();
//                                       if (CANCEL_FLAG.trim().equals("2")){
//                                           myAlertDialog.setMessage("It has been overwritten,  \n" +
//                                                   "so it cannot be updated");
//                                           myAlertDialog.setTypeAlert(false);
//                                           myAlertDialog.show();
//                                           layout_alert.setVisibility(View.GONE);
//
//                                           Clear_itemcode();
//
//                                       }else{
//                                           Overwrite = true;
//                                           txt_status.setText("Re-Sample END");
//                                           Set_sample_layout();
//                                       }

                                   }else if(COUNT_TM_LAST.trim().equals("4")) {

                                       txt_status.setText("Sample END");
                                       Set_sample_layout();

                                   }else {
                                       myAlertDialog.setMessage("Sample No Data");
                                       myAlertDialog.setTypeAlert(false);
                                       myAlertDialog.show();
                                       layout_alert.setVisibility(View.GONE);

                                       Clear_itemcode();

                                   }
                                }
                            }
                        }

                        layout_alert.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Check_LastStocktaking*")
                                .show();
                    }
                }
            }.execute();

        } catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Check_LastStocktaking*")
                    .show();
        }
    }

    private void Check_COUNT_TM3() {
        Log.d(getString(R.string.tag), "Check_COUNT_TM3: " +"|"+COUNT_TM);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "check_COUNT_TM3");
            json.put("MONTH_YEAR", str_month);
            json.put("LOCATION", edt_location.getText().toString().trim());
            json.put("ITEM_NO", str_item_no);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_stocktaking.php",
                    json.toString()) {
                @SuppressLint("StaticFieldLeak")
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try{
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            if (Add_Manual == true) {
                                Gen_SlipNo();
                            } else {
                                AddToMapItem();
                            }
                        }else {
                            txt_status.setText("3RD END");
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Sum_PreviousData*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Sum_PreviousData*")
                    .show();
        }
    }

    private void Sum_PreviousData(String pre_count_tm) {
        Log.d(getString(R.string.tag), "Sum_PreviousData count_tm: " + pre_count_tm+"|"+COUNT_TM);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "sum_quantity");
            json.put("MONTH_YEAR", str_month);
            json.put("COUNT_TM", pre_count_tm);
            json.put("LOCATION", edt_location.getText().toString().trim());
            json.put("ITEM_NO", str_item_no);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_stocktaking.php",
                    json.toString()) {
                @SuppressLint("StaticFieldLeak")
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try{
                        JSONArray jArray = new JSONArray(response);
                        for (int i = 0; i < jArray.length(); i++) {
                            sum_previous_qty = Float.parseFloat(jArray.getJSONObject(i).getString("SUM_QUANTITY"));
                        }
                        Log.d(getString(R.string.tag), "Sum_PreviousData = "+sum_previous_qty);

                        if (Add_Manual == true) {
                            Gen_SlipNo();
                        } else {
                            AddToMapItem();
                        }

                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Sum_PreviousData*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Sum_PreviousData*")
                    .show();
        }
    }

    private void Set_sample_layout() {

        txt_status.setTextColor(Color.parseColor("#FFFFFF"));
        txt_status.setBackgroundResource(R.color.green);

        if (str_previous_result.trim().equals("1")) {
            spinner_result.setSelection(0);

        } else if (str_previous_result.trim().equals("2")) {
            spinner_result.setSelection(1);

        }
        calculate_total();
    }

    private void Clear_itemcode() {
        edt_itemcode.setText("");
        txt_itemcode.setText("");
        txt_itemname.setText("");

        txt_status.setText("-");
        txt_status.setTextColor(Color.parseColor("#FFFFFF"));
        txt_status.setBackgroundResource(R.color.btn_background);
        txt_result.setText("-");
        txt_result.setTextColor(Color.parseColor("#FFFFFF"));
        txt_result.setBackgroundResource(R.color.btn_background);
    }


    private void AddToMapItem() {
        edt_location.setEnabled(false);
        edt_itemcode.setEnabled(false);

        Log.d(getString(R.string.tag), "KEY = " + Key_map);

        mapItems.put(Key_map.trim(), new Stocktaking_item(
                str_month,
                str_inv_wip_type,
                str_slip_no,
                str_wsh_cd,
                "",
                str_location_slip,
                str_item_no,
                str_item_name,
                str_qty_slip,
                str_slip_datetime));
        txt_scan.setText(String.valueOf(mapItems.size()));
        calculate_total();
    }

    private void calculate_total() {
        layout_alert.setVisibility(View.GONE);
        edt_qty.setText("");

        String qty;
        float f_qty, f_total_qty = 0;
        for (String key : mapItems.keySet()){
            Stocktaking_item item = mapItems.get(key);

            qty = item.getQty();
            f_qty = Float.parseFloat(qty);
            f_total_qty = (f_total_qty + f_qty);
            Log.d(getString(R.string.tag), "mapItems.qty : " + String.valueOf(f_qty));
        }
        txt_qty.setText(String.valueOf(decimalFormat.format(f_total_qty)));
    }


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

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

            case R.id.btn_add:
                Add_Qty_Manual();
                break;

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

    private void Confirm_Data() {
        if (mapItems.size() == 0)
            return;
        if (str_main.trim().equals("Stocktaking")) {
            b_confirm = false;
                CANCEL_FLAG = "0";
                if (COUNT_TM.trim().equals("1")) {
                    DOC_STATUS = "0";
                    Insert_Stocktaking();
                } else {
                    if (sum_previous_qty == 0){//เริ่มต้นนับครั้งใหม่ จะไม่มีข้อมูลนับก่อนหน้า ไม่ใช่การนับเพิ่ม
                        sum_previous_qty = last_qty;
                        last_qty = 0;
                    }

                    sum_total = 0;
                    String total = txt_qty.getText().toString().replace(",","");
                    f_total = Float.parseFloat(total);
                    sum_total = (f_total + last_qty);
                    Log.d(getString(R.string.tag), "sum_qty : " + String.valueOf(f_total+"+"+last_qty+" = "+sum_total+" ? "+sum_previous_qty));

                    if (String.valueOf(decimal_format2.format(sum_total)).equals(String.valueOf(decimal_format2.format(sum_previous_qty)))) {
                        DOC_STATUS = "1";
                        Insert_Stocktaking();
                    } else {
                        DOC_STATUS = "2";
                        Insert_Stocktaking();
                    }
                }
        }else {//Sampling
            b_confirm = false;
            Log.d(getString(R.string.tag), "COUNT_TM: " + COUNT_TM);

            String result =  spinner_result.getSelectedItem().toString().trim();
            if (result.trim().equals("Matching")){
                DOC_STATUS = "1";
            }else {
                DOC_STATUS = "2";
            }

            if (Overwrite == true){
                CANCEL_FLAG = "2";
                Alert_confOverwrite();
            }else {
                CANCEL_FLAG = "0";
                Insert_Stocktaking();
            }
        }
    }
    private void Clear_layout() {
        b_confirm = true;
        mapItems.clear();
        edt_location.setEnabled(true);
        edt_itemcode.setEnabled(true);
        edt_location.setText("");
        edt_itemcode.setText("");
        txt_itemcode.setText("");
        txt_itemname.setText("");
        txt_qty.setText("");
        txt_scan.setText(String.valueOf(mapItems.size()));
        txt_status.setText("-");
        txt_status.setTextColor(Color.parseColor("#FFFFFF"));
        txt_status.setBackgroundResource(R.color.btn_background);
        txt_result.setText("-");
        txt_result.setTextColor(Color.parseColor("#FFFFFF"));
        txt_result.setBackgroundResource(R.color.btn_background);
        int_run_slip = 0;
        sum_previous_qty = 0;
        Overwrite = false;
        Scan_location = false;
        Add_Manual = false;
        DOC_STATUS = "";
        CANCEL_FLAG = "";
        Result = "";
        Key_map = "";
    }

    private void Clear_Data() { //delete last label only
        if (mapItems.size() == 0)
            return;

        Log.d(getString(R.string.tag), "mapItems.size : " + String.valueOf(mapItems.size()));
        Log.d(getString(R.string.tag), "Key Slip No. : " + Key_map.trim());
        mapItems.remove(Key_map.trim());

        txt_scan.setText(String.valueOf(mapItems.size()));
        Log.d(getString(R.string.tag), "1mapItems.size : " + String.valueOf(mapItems.size()));
        calculate_total();

        if (mapItems.size() == 0) {//not clear location
            edt_location.setEnabled(true);
            edt_itemcode.setEnabled(true);

            edt_itemcode.setText("");
            txt_itemname.setText("");
            txt_qty.setText("");

            txt_status.setText("-");
            txt_status.setTextColor(Color.parseColor("#FFFFFF"));
            txt_status.setBackgroundResource(R.color.btn_background);
            txt_result.setText("-");
            txt_result.setTextColor(Color.parseColor("#FFFFFF"));
            txt_result.setBackgroundResource(R.color.btn_background);
            int_run_slip = 0;
            sum_previous_qty = 0;
            Overwrite = false;
            Add_Manual = false;
            DOC_STATUS = "";
            CANCEL_FLAG = "";
            Result = "";

            str_item_no = "";
            str_item_name = "";
            str_wsh_cd = "";
            str_location_slip = "";
            str_qty_slip = "";
            str_slip_no = "";
            Key_map = "";
        }
    }

    private void Alert_confOverwrite() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.layout_dialog_overwrite, null);
        builder.setView(view);
        builder.setCancelable(false);

        TextView Message = (TextView) view.findViewById(R.id.txt_message);
        Button btn_alert_ok = (Button)view.findViewById(R.id.btn_alert_ok);
        Button btn_alert_cancel = (Button)view.findViewById(R.id.btn_alert_cancel);
        final AlertDialog ad = builder.show();

        btn_alert_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Overwrite_Stocktaking();
                ad.dismiss();
            }
        });

        btn_alert_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
    }

    private void Insert_Stocktaking() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, Insert data...");

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

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "add");

            JSONArray jsonArray = new JSONArray();
            for (String key : mapItems.keySet()){
                Stocktaking_item item = mapItems.get(key);
                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("MONTH_YEAR", item.getMonth_year());
                jsonParams.put("INV_WIP_TYPE", item.getType());
                jsonParams.put("SLIP_NO", item.getSlip_no());
                jsonParams.put("WHS_CD", item.getWhs_cd());
                jsonParams.put("WS_CD", item.getWs_cd());
                jsonParams.put("LOCATION", edt_location.getText().toString().trim());
                jsonParams.put("ITEM_NO", item.getItem_no());
                jsonParams.put("QUANTITY", item.getQty());
                jsonParams.put("CANCEL_FLAG",CANCEL_FLAG);
                jsonParams.put("COUNT_TM", COUNT_TM);
                jsonParams.put("DOC_STATUS", DOC_STATUS);
                jsonParams.put("ENTRY_DATE", datetime_to_server);
                jsonParams.put("CHG_PGM", CHG_PGM);
                jsonParams.put("USER_ID", Settings.getLoginUser().getId());
                jsonParams.put("LABELPRINT_DATE", item.getSlip_datetime());

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }
            json.put("datas",jsonArray);
            if (jsonArray.length() == 0)
                return;

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_stocktaking.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");
                        layout_alert.setVisibility(View.GONE);

                        if (status.equals("success") && affected_rows > 0) {
                            layout_alert.setVisibility(View.GONE);
                            if (COUNT_TM.trim().equals("1")||COUNT_TM.trim().equals("4")||COUNT_TM.trim().equals("5")) {
                                myAlertDialog.setMessage("Completion of registration");
                                myAlertDialog.setTypeAlert(true);
                                myAlertDialog.show();

                                Clear_layout();

                                //re query count job
                                if (COUNT_TM.trim().equals("4")||COUNT_TM.trim().equals("5")){
                                    Count_Job();
                                }

                            }else {//step 2,3
                                if (DOC_STATUS.trim().equals("1")){
                                    myAlertDialog.setMessage("Matching");
                                    myAlertDialog.setTypeAlert(true);
                                    myAlertDialog.show();
                                    layout_alert.setVisibility(View.GONE);

                                    Update_DocStatus(COUNT_TM, str_month, str_item_no, edt_location.getText().toString().trim(),"1");
                                }else {
                                    myAlertDialog.setMessage("Unmatching\n\n"
                                            +"COUNT_TM "+PRE_COUNT_TM+" : "+String.valueOf(decimal_format2.format(sum_previous_qty))
                                            +"\n\n"
                                            +"COUNT_TM "+COUNT_TM+" : "+String.valueOf(decimal_format2.format(sum_total)));
                                    myAlertDialog.setTypeAlert(false);
                                    myAlertDialog.show();
                                    layout_alert.setVisibility(View.GONE);

                                    Update_DocStatus(COUNT_TM, str_month, str_item_no, edt_location.getText().toString().trim(),"2");
                                }
                            }

                        }else {
                            myAlertDialog.setMessage("Can't register Stocktaking");
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Insert_Stocktaking*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Insert_Stocktaking*")
                    .show();
        }
    }



    private void Update_DocStatus(String count_tm, String month_year, String item_no, String location, String doc_status) {
        Log.d(getString(R.string.tag), "Update_DocStatus");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "update_doc_status");
            json.put("ENTRY_DATE", datetime_to_server);
            json.put("DOC_STATUS", doc_status);
            json.put("MONTH_YEAR", month_year);
            json.put("COUNT_TM", count_tm);
            json.put("LOCATION", location);
            json.put("ITEM_NO", item_no);

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

                        Clear_layout();

                        if (!status.equals("success") || affected_rows == 0) {
                            myAlertDialog.setMessage("Can't update DOC_STATUS");
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);
                        }

                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Update_DocStatus*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Update_DocStatus*")
                    .show();
        }

    }

    private void Overwrite_Stocktaking() {
        //update CANCEL_FLAG = 1 แล้ว Insert ใหม่ CANCEL_FLAG = 2
        Log.d(getString(R.string.tag), "Overwrite: " + CANCEL_FLAG+"|"+COUNT_TM);
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        datetime_to_server = format_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "datetime_to_server: " + datetime_to_server);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "cancel");
            json.put("MONTH_YEAR", str_month);
            json.put("COUNT_TM", COUNT_TM);
            json.put("LOCATION", edt_location.getText().toString().trim());
            json.put("ITEM_NO", edt_itemcode.getText().toString().trim());
            json.put("ENTRY_DATE", datetime_to_server);

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

                        }else{

                            myAlertDialog.setMessage("Can't register CANCEL_FLAG");
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);

                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Overwrite_Stocktaking*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Overwrite_Stocktaking*")
                    .show();
        }
    }

    private void Add_Qty_Manual() {
        str_slip_datetime = "";
        Add_Manual = true;

        String location = edt_location.getText().toString().trim();
        String item_no = edt_itemcode.getText().toString().trim();
        String qty = edt_qty.getText().toString().replace(",","");
        if (qty.trim().equals("")){
            qty = "0";
        }
        float manual_qty = Float.parseFloat(qty);
        if (location.trim().equals("")||item_no.trim().equals("")||manual_qty <= 0)
            return;

        if (mapItems.size() == 0){
            if (Scan_location == false){//manual location
                //check location master
                String[] a = new String[0];
                Check_location("Add_qty", a,item_no);

            }else {

                Check_ItemMaster(item_no);
            }
        }else{

            Gen_SlipNo();

        }
    }

    private void Gen_SlipNo() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");

        edt_location.setEnabled(false);
        edt_itemcode.setEnabled(false);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "query");
            json.put("ITEM_CTR_CD", ITEM_CTR_CD);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_numbering_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){
                            myAlertDialog.setMessage("Not found ITEM_CTR_CD "+ITEM_CTR_CD);
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                slip_HEADER = jArray.getJSONObject(i).getString("HEADER");
                                slip_LAST = jArray.getJSONObject(i).getString("LAST_NUMBER");
                                slip_COUNT = jArray.getJSONObject(i).getString("COUNT_NUMBER");
                                slip_MONTH_YEAR = jArray.getJSONObject(i).getString("MONTH_YEAR");

                            }
                            int int_month_year, int_slip_month_year;
                            int_month_year = Integer.parseInt(str_month);
                            int_slip_month_year = Integer.parseInt(slip_MONTH_YEAR);
                            Log.d(getString(R.string.tag), "MONTH_YEAR : " + str_month + " | " + slip_MONTH_YEAR);

                            if (int_month_year < int_slip_month_year) {//นับย้อนหลัง

                                Query_LastNumber();

                            } else {
                                if (int_month_year == int_slip_month_year) {//นับตรงเดือน
                                    slip_COUNT_int = Integer.parseInt(slip_COUNT);
                                    slip_COUNT_int = (slip_COUNT_int + 1);

                                } else {//เริ่มเดือนถัดไป นับแบบปกติ int_month_year > int_slip_month_year
                                    slip_COUNT_int = 1;
                                }

                                slip_COUNT = String.format("%6s", slip_COUNT_int).replace(' ', '0');

                                slip_LAST_int = Integer.parseInt(slip_LAST);
                                slip_LAST_int = (slip_LAST_int + 1);
                                //update Numbering Master
                                Update_Numbering(slip_COUNT_int, slip_LAST_int);

                                String fm_slip = str_month.substring(2);
                                str_slip_no = slip_HEADER + fm_slip + slip_COUNT;
                                Log.d(getString(R.string.tag), "str_slip_no: " + str_slip_no);

                                Key_map = str_slip_no;
                                Log.d(getString(R.string.tag), "manual key: " + Key_map);

                                //add map manual
                                mapItems.put(Key_map.trim(), new Stocktaking_item(
                                        str_month,
                                        str_inv_wip_type,
                                        str_slip_no,
                                        "",
                                        "",
                                        "",
                                        edt_itemcode.getText().toString().trim(),
                                        txt_itemname.getText().toString().trim(),
                                        edt_qty.getText().toString().replace(",", ""),
                                        ""));

                                txt_scan.setText(String.valueOf(mapItems.size()));
                                calculate_total();
                            }
                        }

                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Gen_SlipNo*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Gen_SlipNo*")
                    .show();
        }
    }

    private void Query_LastNumber() {
        int_run_slip = (int_run_slip + 1);
        String[]data = ITEM_CTR_CD.split("-");
        String slip = data[0]+str_month.substring(2);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "query_last_slip");
            json.put("MONTH_YEAR", str_month);
            json.put("SLIP_NO",slip+"%");

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/nst_stocktaking.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){
                            str_slip_no = slip+str_month.substring(2)+String.format("%6s", String.valueOf(int_run_slip)).replace(' ', '0');
                        }else{
                            for(int i=0;i<jArray.length();i++) {
                                SLIP_NUMBER = jArray.getJSONObject(i).getString("SLIP_NO")=="null"?"":jArray.getJSONObject(i).getString("SLIP_NO");
                            }

                            if(SLIP_NUMBER.trim().equals("")){

                                str_slip_no = slip + String.format("%6s", String.valueOf(int_run_slip)).replace(' ', '0');
                                Log.d(getString(R.string.tag), "str_slip_no.null: " + str_slip_no);
                            }else {

                                String running = SLIP_NUMBER.substring(6);
                                int int_running = Integer.parseInt(running);
                                int_running = (int_running + int_run_slip);

                                slip_COUNT = String.format("%6s", String.valueOf(int_running)).replace(' ', '0');
                                str_slip_no = SLIP_NUMBER.substring(0, 6) + slip_COUNT;
                                Log.d(getString(R.string.tag), "str_slip_no: " + str_slip_no);
                            }
                        }
                        Key_map = str_slip_no;
                        Log.d(getString(R.string.tag), "manual key: " + Key_map);
                        //add map manual
                        mapItems.put(Key_map.trim(), new Stocktaking_item(
                                str_month,
                                str_inv_wip_type,
                                str_slip_no,
                                "",
                                "",
                                "",
                                edt_itemcode.getText().toString().trim(),
                                txt_itemname.getText().toString().trim(),
                                edt_qty.getText().toString().replace(",", ""),
                                ""));

                        txt_scan.setText(String.valueOf(mapItems.size()));
                        calculate_total();

                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Query_LastNumber*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Query_LastNumber*")
                    .show();
        }

    }

    private void Update_Numbering(int slip_count_int, int slip_last_int) {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        datetime_to_server = format_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "datetime_to_server: " + datetime_to_server);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "update");
            json.put("LAST_NUMBER", String.valueOf(slip_last_int));
            json.put("COUNT_NUMBER", String.valueOf(slip_count_int));
            json.put("CHG_DATE", datetime_to_server);
            json.put("ITEM_CTR_CD", ITEM_CTR_CD);
            json.put("USER_ID", Settings.getLoginUser().getId());
            json.put("CHG_PGM", CHG_PGM);

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

                            myAlertDialog.setMessage("Can't Update Numbering");//("Location not found")
                            myAlertDialog.setTypeAlert(false);
                            myAlertDialog.show();
                            layout_alert.setVisibility(View.GONE);

                        }

                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage()+"\n"+"*Update_Numbering*")
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(StocktakingActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage()+"\n"+"*Update_Numbering*")
                    .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) {
                        Confirm_Data();
                    }
                    break;

                case P3:
                    if (str_main.trim().equals("Stocktaking")) {
                        Clear_Data();
                    }
                    break;

                case P4:
                    if (str_main.trim().equals("Stocktaking")) {
                        Add_Qty_Manual();
                    }
                    break;

            }
        }

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