package com.tomastc.ht_nki;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.ht_nki.ListData.InboundRack_DetailItem_list;
import com.tomastc.ht_nki.ListData.Location_list;
import com.tomastc.ht_nki.lib.KeyMapping;
import com.tomastc.ht_nki.lib.Scanner;
import com.tomastc.ht_nki.lib.Settings;
import com.tomastc.ht_nki.lib.common.AsyncHttpClient;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class InboundRackScheduleDetail_Activity extends Scanner implements View.OnClickListener {

    TextView txt_user, txt_device, txt_ticket_no, txt_qrt_total,edt_qty,txt_qty_total;
    Spinner dropdown;
    Bundle bundle;
    Integer sum_total =0;
    Integer sum_total_order =0;
    String str_ticket_no , str_event , str_qty ,str_unit_qty,str_state,str_location="";
    Map<String, InboundRack_DetailItem_list> map_inbound_rack_detail_item;
    List<InboundRack_DetailItem_list> list_inbound_rack_detail_label;
    Boolean clear_data,incorrect_data,confirm_true_data;
    SharedPreferences Preferences;
    RelativeLayout popupLayout4;
    Button btn_confirm,btn_ok,btn_cancel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inbound_rack_detail);

        list_inbound_rack_detail_label = new ArrayList<InboundRack_DetailItem_list>();
        map_inbound_rack_detail_item = new LinkedHashMap<>();

        clear_data = false;
        //incorrect_data = false;
        confirm_true_data = false;

        txt_user = findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());
        txt_device = findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());

        dropdown = findViewById(R.id.spinner1);

        txt_qrt_total = findViewById(R.id.txt_qrt_total);
        txt_ticket_no = findViewById(R.id.txt_ticket_no);

        popupLayout4 = (RelativeLayout) findViewById(R.id.popupLayout4);
        popupLayout4.setVisibility(GONE);
        btn_ok = (Button) findViewById(R.id.btn_ok);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);

        edt_qty = (EditText) findViewById(R.id.txt_qty);
        txt_qty_total = (TextView) findViewById(R.id.txt_qty_total);
        txt_qrt_total.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                edt_qty.setText("");

                edt_qty.setInputType(InputType.TYPE_NULL);
                edt_qty.requestFocus();


                popupLayout4.setVisibility(View.VISIBLE);
                txt_qty_total.setText("/"+sum_total_order.toString().replace(".00",""));



            }
        });

        edt_qty.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {

                    btn_ok.performClick();


                    return true;
                }
                return false;
            }
        });


        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edt_qty.getText().toString().length() > 0) {
                    popupLayout4.setVisibility(GONE);
                    Integer act_qty = Integer.parseInt(edt_qty.getText().toString());
                    if (act_qty > sum_total_order) {

                        new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("The specified quantity is too high.")
                                .show();


                    } else {


                        sum_total = 0;
                        sum_total = act_qty;
                        txt_qrt_total.setText(act_qty.toString() + " " + str_unit_qty);


                    }


                }
            }
        });


        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupLayout4.setVisibility(GONE);
                edt_qty.setText("");
            }
        });

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId()) {

            if (popupLayout4.getVisibility() == VISIBLE) {
                switch (KeyMapping.fromId(keyCode)) {
                    case P1:

                        btn_cancel.performClick();
                        break;

                }



            }
            else {
                switch (KeyMapping.fromId(keyCode)) {
                    case P1:
                        finish();
                        break;
                }
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        bundle = getIntent().getExtras();
        str_ticket_no = bundle.getString("ticket_no");
        str_state = bundle.getString("state");
        txt_ticket_no.setText(str_ticket_no);

        if (Objects.equals(str_state, "click")){
            load_inbound_rack_detail();
        }else {
            load_inbound_rack_detail_scan();
        }
    }

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

        }
    }

    private void load_inbound_rack_detail(){
        map_inbound_rack_detail_item.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "INBOUND/RACK/DETAIL");
            json.put("ticket_no", str_ticket_no);

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

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);

                        if (jArray.length() == 0) {
                            txt_ticket_no.setText("");
                            Toast.makeText(InboundRackScheduleDetail_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                        }else {
                            for(int i = 0; i < jArray.length(); i++){
                                Log.d("TOT","Data length : "+jArray.get(i));
                                str_unit_qty = jArray.getJSONObject(i).getString("unit_qty").trim();
                                sum_total_order = sum_total_order + jArray.getJSONObject(i).getInt("qty");
                                map_inbound_rack_detail_item.put( jArray.getJSONObject(i).getString("id").trim(),
                                        new InboundRack_DetailItem_list(
                                                jArray.getJSONObject(i).getString("id").trim(),
                                                "",
                                                jArray.getJSONObject(i).getString("order_no").trim(),
                                                jArray.getJSONObject(i).getString("ticket_no").trim(),
                                                jArray.getJSONObject(i).getString("parts_no").trim(),
                                                jArray.getJSONObject(i).getString("parts_name").trim(),
                                                jArray.getJSONObject(i).getString("qty").trim(),
                                                jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                jArray.getJSONObject(i).getString("action_act_qty").trim(),
                                                jArray.getJSONObject(i).getString("status").trim(),
                                                jArray.getJSONObject(i).getString("lot_no").trim(),
                                                jArray.getJSONObject(i).getString("bc_tire").trim()

                                        ));
                            }
                        }

                        set_view_location_eventClick();

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

    private void set_view_location_eventClick(){

        String Location_QC = "";
        List<String> locationQcList = new ArrayList<>();

        locationQcList.add("-");

        for (String kk : Settings.getMap_location().keySet()){
            Location_list location_list = Settings.getMap_location().get(kk);
            if (location_list.getQc_area().trim().equals("0")){
                Location_QC = location_list.getId();
                locationQcList.add(Location_QC);
                Log.d(getString(R.string.tag), "----- > Location List  on loop : " + Location_QC);
            }
        }

        ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,locationQcList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = parent.getItemAtPosition(position).toString();
                Preferences = getSharedPreferences("location", MODE_PRIVATE);
                SharedPreferences.Editor editor = Preferences.edit();
                editor.putString("location", selectedItem);
                editor.clear();
                editor.apply();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        set_view_schedule();

    }

    private void set_view_location_eventScan(){

        String Location_QC = "";
        List<String> locationQcList = new ArrayList<>();

        locationQcList.add("-");

        for (String kk : Settings.getMap_location().keySet()){
            Location_list location_list = Settings.getMap_location().get(kk);
            if (location_list.getQc_area().trim().equals("0")){
                Location_QC = location_list.getId();
                locationQcList.add(Location_QC);
                Log.d(getString(R.string.tag), "----- > Location List  on loop : " + Location_QC);
            }
        }

        ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,locationQcList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dropdown.setAdapter(adapter);
        dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = parent.getItemAtPosition(position).toString();
                Preferences = getSharedPreferences("location", MODE_PRIVATE);
                SharedPreferences.Editor editor = Preferences.edit();
                editor.putString("location", selectedItem);
                editor.clear();
                editor.apply();
                str_location = selectedItem.equals("-")?"":selectedItem;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


        set_view_schedule();

    }
    private void load_inbound_rack_detail_scan(){
        map_inbound_rack_detail_item.clear();

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "INBOUND/RACK/DETAIL");
            json.put("ticket_no", str_ticket_no);

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

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);

                        if (jArray.length() == 0) {
                            Toast.makeText(InboundRackScheduleDetail_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                            dialog_massage_not_match();
                            event_clear();
                        }else {

                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            Log.d("TOT","Status ====> : "+status_label);


                                for(int i = 0; i < jArray.length(); i++){
                                    Log.d("TOT","Data length : "+jArray.get(i));
                                    str_unit_qty = jArray.getJSONObject(i).getString("unit_qty").trim();
                                    sum_total_order = sum_total_order + jArray.getJSONObject(i).getInt("qty");
                                    map_inbound_rack_detail_item.put( jArray.getJSONObject(i).getString("id").trim(),
                                            new InboundRack_DetailItem_list(
                                                    jArray.getJSONObject(i).getString("id").trim(),
                                                    "",
                                                    jArray.getJSONObject(i).getString("order_no").trim(),
                                                    jArray.getJSONObject(i).getString("ticket_no").trim(),
                                                    jArray.getJSONObject(i).getString("parts_no").trim(),
                                                    jArray.getJSONObject(i).getString("parts_name").trim(),
                                                    jArray.getJSONObject(i).getString("qty").trim(),
                                                    jArray.getJSONObject(i).getString("unit_qty").trim(),
                                                    jArray.getJSONObject(i).getString("action_act_qty").trim(),
                                                    jArray.getJSONObject(i).getString("status").trim(),
                                                    jArray.getJSONObject(i).getString("lot_no").trim(),
                                                    jArray.getJSONObject(i).getString("bc_tire").trim()
                                            ));
                                    Log.d("TOT","Data length map ===> : "+ map_inbound_rack_detail_item.get(i));
                                }


                            set_view_location_eventScan();
                        }

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

    private void set_view_schedule(){

        list_inbound_rack_detail_label.clear();

        int no = 0;
        int TotalSumQTY = 0;
        double TotalSumAction_Act_QTY = 0.00;
        String value_unit_qty = "";

        for (String key : map_inbound_rack_detail_item.keySet()) {
            no = (no + 1);
            InboundRack_DetailItem_list item = map_inbound_rack_detail_item.get(key);
            double qty = Double.parseDouble(item.getQty());
            value_unit_qty = String.valueOf(item.getUnit_qty());
            TotalSumQTY += qty;

            list_inbound_rack_detail_label.add(new InboundRack_DetailItem_list(
                    item.getId(),
                    String.valueOf(no),
                    item.getOrder_no(),
                    item.getTicket_no(),
                    item.getParts_no(),
                    item.getParts_name(),
                    item.getQty(),
                    item.getUnit_qty(),
                    item.getAction_act_qty(),
                    item.getStatus(),
                    item.getLot_no(),
                    item.getBc_tire()
            ));
        }

        Log.d("TOT","Data Map List  set view :"+list_inbound_rack_detail_label.size());

        if (TotalSumQTY == 0){
            txt_qrt_total.setText("0 PCS");
        }else {
            txt_qrt_total.setText(TotalSumQTY+"  "+value_unit_qty);
        }



    }

    private void set_view_schedule_scan(){
        list_inbound_rack_detail_label.clear();
        int no = 0;
        double TotalSumQTY = 0.00;
        double TotalSumAction_Act_QTY = 0.00;
        String value_unit_qty = "";

        for (String key : map_inbound_rack_detail_item.keySet()) {
            no = (no + 1);
            InboundRack_DetailItem_list item = map_inbound_rack_detail_item.get(key);
            double qty = Double.parseDouble(item.getQty());
            value_unit_qty = String.valueOf(item.getUnit_qty());
            TotalSumQTY += qty;

            list_inbound_rack_detail_label.add(new InboundRack_DetailItem_list(
                    item.getId(),
                    String.valueOf(no),
                    item.getOrder_no(),
                    item.getTicket_no(),
                    item.getParts_no(),
                    item.getParts_name(),
                    item.getQty(),
                    item.getUnit_qty(),
                    item.getAction_act_qty(),
                    item.getStatus(),
                    item.getLot_no(),
                    item.getBc_tire()
            ));
        }

        Log.d("TOT","Data Map List  set view :"+list_inbound_rack_detail_label.size());

        if (TotalSumQTY == 0.00){
            txt_qrt_total.setText("0  PCS");
        }else {
            txt_qrt_total.setText(TotalSumQTY+"  "+value_unit_qty);
        }
    }

    private void event_clear(){
        clear_data = true;

        ///===> set view
        str_ticket_no = "";
        txt_ticket_no.setText("-");

        ///====> snipper
        String[] dropdown_items = new String[]{"-"};
        ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,dropdown_items);
        dropdown.setAdapter(adapter);
        dropdown.setSelection(0);
        ///====> value actual
        txt_qrt_total.setText(" 0 PCS");





    }
    private void event_confirm(){



        if (str_location.equals("")){
            dialog_massage_insufficient();

        }
        else  if (!str_ticket_no.equals("")){
            confirm_inbound_rack();
        }


    }
    private void confirm_inbound_rack(){
        try {
            JSONObject json = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();


           Preferences = getSharedPreferences("location", MODE_PRIVATE);
           String location_name =  Preferences.getString("location", "");
            Log.d(getString(R.string.tag),"location_name : "+ location_name);

            if(sum_total==0)
            {
                sum_total = sum_total_order;
            }

            for (String key : map_inbound_rack_detail_item.keySet()){
                InboundRack_DetailItem_list item = map_inbound_rack_detail_item.get(key);
                Log.d("Log data ",item.getId().trim());

                jsonParams.put("ref_sch_id", item.getId());
                jsonParams.put("create_user_id", Settings.getLoginUser().getName());
                jsonParams.put("item_id", item.getParts_no());
                jsonParams.put("unit_qty", item.getUnit_qty());
                jsonParams.put("item_name", item.getParts_name());
                jsonParams.put("package_id", item.getUnit_qty());
                jsonParams.put("location_id", location_name);// status = 1
                jsonParams.put("location_name", location_name);// status = 1
                jsonParams.put("package_qty", item.getQty());
                jsonParams.put("lot_no", item.getLot_no()  );
                jsonParams.put("order_no",  item.getOrder_no().contains("null")?"":item.getOrder_no()); //"0000230868"  / item.getOrderNumber
                jsonParams.put("qty", item.getQty());
                jsonParams.put("slip_divide", "0");
                jsonParams.put("ng", "0");
                jsonParams.put("supplier_name", "");
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("supplier_id", "0");
                jsonParams.put("label_id", "1");
                jsonParams.put("status", "2");
                jsonParams.put("ticket_no",item.getTicket_no().trim().trim());
                jsonParams.put("bc_tire", item.getBc_tire().trim());
                jsonParams.put("process_type", "RACK");
                jsonParams.put("act_qty", sum_total.toString());
                jsonParams.put("order_qty", sum_total_order.toString());
                jsonParams.put("userid",Settings.getLoginUser().getName().toString());

                JSONObject jsonObj = new JSONObject(jsonParams);
                jsonArray.put(jsonObj);
            }

            ///===> Request
            json.put("cmd", "INBOUND/RACK/CONFIRM");
            json.put("value",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.e("T-T","Data Response : " +response);

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int affectedRows = jsonObject.getInt("affected_rows");

                        if (affectedRows == 0) {
                            Toast.makeText(InboundRackScheduleDetail_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                            Log.d("JSON", "Affected rows: " + affectedRows);
                            dialog_massage_insufficient();
                            event_clear();
                        }else {
                            Toast.makeText(InboundRackScheduleDetail_Activity.this, "complete", Toast.LENGTH_SHORT).show();
                            dialog_massage_complete();
                            event_clear();
                        }

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

                }

            }.execute();

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

        }

    }
    private void dialog_massage_not_match(){

        TextView customTextView = new TextView(InboundRackScheduleDetail_Activity.this);
        customTextView.setText("Ticket No do not match");
        customTextView.setTextColor(Color.RED);
        customTextView.setTextSize(16);
        customTextView.setGravity(Gravity.CENTER);

        new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("WARNING")
                //.setContentText("Ticket No do not match")
                .setCustomView(customTextView)
                .setConfirmText("NG")
                .setConfirmButtonBackgroundColor(Color.RED)
                .show();


    }
    private void dialog_massage_insufficient(){
        TextView customTextView = new TextView(InboundRackScheduleDetail_Activity.this);
        customTextView.setText("Insufficient information");
        customTextView.setTextColor(Color.RED);
        customTextView.setTextSize(16);
        customTextView.setGravity(Gravity.CENTER);

        new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("WARNING")
                //.setContentText("Ticket No do not match")
                .setCustomView(customTextView)
                .setConfirmText("NG")
                .setConfirmButtonBackgroundColor(Color.RED)
                .show();
    }
    private void dialog_massage_complete(){
        new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("INFORMATION")
                .setContentText("Operation complete!")
                .show();

    }

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

        String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
        String resultToken = tokens[0];

        Log.d("TOT","Data Scan  : "+resultToken);
        Log.d("TOT","Data Scan  : "+tokens.length);

        if (tokens.length == 1){

            try {
                JSONObject json = new JSONObject();
                json.put("cmd", "INBOUND/RACK/DETAIL");
                json.put("ticket_no", resultToken);

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

                            JSONObject jsonObject = new JSONObject(response);
                            String value = jsonObject.getString("value");
                            JSONArray jArray = new JSONArray(value);

                            if (jArray.length() == 0 )
                            {


                                str_location = data;


                            }
                            else
                            {

                                str_ticket_no = jArray.getJSONObject(0).getString("ticket_no").trim();
                                txt_ticket_no.setText(str_ticket_no);
                                load_inbound_rack_detail();





                            }



                        }catch (JSONException e) {
                            new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("Can not connect server")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();





            }catch (JSONException e) {
                new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Can not connect server")
                        .setContentText(e.getMessage())
                        .show();
            }


        String Location_QC = "";
        List<String> locationQcList = new ArrayList<>();
        for (String kk : Settings.getMap_location().keySet()){
            Location_list location_list = Settings.getMap_location().get(kk);
            if (location_list.getQc_area().trim().equals("0")){
                Location_QC = location_list.getId();
                locationQcList.add(Location_QC);
                str_location = data;
            }
        }

        Log.d("====> ","======> Data Location  :"+locationQcList);

            if (locationQcList.contains(resultToken)) {
                //set_dropdown(resultToken);
                ArrayAdapter<String> adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,locationQcList);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dropdown.setAdapter(adapter);
                int defaultPosition = locationQcList.indexOf(resultToken);
                dropdown.setSelection(defaultPosition);
                dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        String selectedItem = parent.getItemAtPosition(position).toString();
                        Preferences = getSharedPreferences("location", MODE_PRIVATE);
                        SharedPreferences.Editor editor = Preferences.edit();
                        editor.putString("location", selectedItem);
                        editor.clear();
                        editor.apply();
                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
            }

        }else {
                  new SweetAlertDialog(InboundRackScheduleDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Invalid QR code!")
                    .show();
        }

    }



}
