package com.tomastc.ht_nki;

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

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.ht_nki.Adapter.Outbound_PickingDetail_Adapter;
import com.tomastc.ht_nki.ListData.OutboundPickingDetail_item;
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 cn.pedant.SweetAlert.SweetAlertDialog;

public class OutboundPickingDetail_Activity extends Scanner implements View.OnClickListener,ClickRowOutBounddetail {

    TextView txt_document_no,txt_total;
    Bundle bundle;
    String str_document_no , str_event;
    TextView txt_user, txt_device;
    RecyclerView view_picking_detail;
    Map<String, OutboundPickingDetail_item> map_item;
    List<OutboundPickingDetail_item> list_item,list_item_ng;
    Outbound_PickingDetail_Adapter adapter;

    Button btn_ok,btn_cancel;

    EditText edt_qty;

    TextView txt_qty_total;
    String  str_id,leader_confirm;

    Boolean leader_scan = false;

    String  ticket_no_check="";
    Dialog dialog;

    RelativeLayout popupLayout4,popupLayout5;

    String lbl_item_id,lbl_tire_week,lbl_ticket_no,lbl_location_id,lbl_qty;



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

        list_item = new ArrayList<OutboundPickingDetail_item>();
        list_item_ng = new ArrayList<OutboundPickingDetail_item>();
        map_item = new LinkedHashMap<>();

        txt_document_no = findViewById(R.id.txt_document_no);
        txt_total  =  findViewById(R.id.txt_total);

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

        popupLayout4 = (RelativeLayout) findViewById(R.id.popupLayout4);
        popupLayout4.setVisibility(GONE);
        popupLayout5 = (RelativeLayout) findViewById(R.id.popupLayout5);
        popupLayout5.setVisibility(GONE);

        btn_ok = (Button) findViewById(R.id.btn_ok);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        txt_qty_total = (TextView)findViewById(R.id.txt_qty_total);


        edt_qty = (EditText) findViewById(R.id.txt_real_qty);
        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);


                    for (int i = 0; i < list_item.size(); i++) {


                        try {
                            Double item_qty = Double.parseDouble(list_item.get(i).getQty().toString());
                            Double label_qty = Double.parseDouble(list_item.get(i).getAction_act_qty().toString());
                            String id = list_item.get(i).getParts_no() + list_item.get(i).getLot_no() + list_item.get(i).getLocation_id() + list_item.get(i).getTicket_no();


                            if (id.equals(str_id)) {


                                Double edit_qty = Double.parseDouble(edt_qty.getText().toString());
                                if (edit_qty > item_qty && item_qty > 0) {

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

                                    break;


                                } else {

                                    list_item.get(i).setAction_act_qty(edt_qty.getText().toString().replace(".00", ""));
                                    if (edit_qty < item_qty && item_qty > 0) {
                                        list_item.get(i).setStatus("NG");

                                    } else {

                                        list_item.get(i).setStatus("OK");
                                        Double ticket_remain = label_qty - edit_qty;
                                        create_new_ticket(edit_qty, ticket_remain);

                                    }


                                }


                            }


                        } catch (Exception err) {
                            err.printStackTrace();
                        }

                    }
                    set_view_data(list_item);
                }
            }

        });


        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_document_no = bundle.getString("do_no");
        str_event = bundle.getString("event");

        txt_document_no.setText(str_document_no);

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

        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());

        if (str_event.equals("S")){
            load_data_picking_det(str_document_no);
        }else {
            load_data_picking_det(str_document_no);
        }
        scan_ticket_no("000000");

    }

    private void create_new_ticket(Double new_qty, Double remain_qty)
    {


        try {

            JSONObject json = new JSONObject();
            json.put("cmd", "NEW/TICKET/LABEL");
            json.put("item_id",lbl_item_id);
            json.put("tire_week",lbl_tire_week);
            json.put("ticket_no",lbl_ticket_no);
            json.put("location_id",lbl_location_id);
            json.put("qty_new",new_qty.toString());
            json.put("qty_old",remain_qty.toString());
            json.put("userid",Settings.getLoginUser().getId());

            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 user: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");

                        if (!status.equals("success")){
                            Toast.makeText(OutboundPickingDetail_Activity.this, "Not found user", Toast.LENGTH_SHORT).show();

                        }else {


                            lbl_item_id = "";
                            lbl_tire_week = "";
                            lbl_ticket_no = "";
                            lbl_location_id = "";
                            lbl_qty = "";

                            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("INFORMATION")
                                    .setContentText("Print the label from PC.")
                                    .setConfirmText("OK")
                                    .show();

                        }

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



    }
    private void load_data_picking_det(String str_document_no){
        try {
            map_item.clear();
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/PICKING/SCHEDULE/DETAIL");
            json.put("do_no",str_document_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 outbound Detail: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        if (jArray.length() == 0){
                            Toast.makeText(OutboundPickingDetail_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                            dialog_massage_not_match();
                            clear_data();
                        }else {
                            int count = 1;
                            int totalQty = 0;
                            int totalActionActQty = 0;
                            for(int i = 0; i < jArray.length(); i++) {
                                String SumQty = jArray.getJSONObject(i).getString("qty");
                                String SumActionActQty = jArray.getJSONObject(i).getString("action_act_qty").trim();
                                try {
                                    int Qty = Integer.parseInt(SumQty);
                                    int ActionActQty = Integer.parseInt(SumActionActQty);
                                    totalQty += Qty;
                                    totalActionActQty += ActionActQty;

                                    Log.e("ToT", "====> SumQty : " + totalQty);
                                    Log.e("ToT", "====> SumActionActQty : " + totalActionActQty);

                                }catch (NumberFormatException e) {
                                    Log.e("ToT", "Invalid SumQty : " + totalQty);
                                    Log.e("ToT", "Invalid SumActionActQty : " + totalActionActQty);
                                }


                                list_item.add(new OutboundPickingDetail_item(
                                        String.valueOf(count+i),
                                        jArray.getJSONObject(i).getString("id").trim(),
                                        jArray.getJSONObject(i).getString("invoice_no").trim(),
                                        jArray.getJSONObject(i).getString("order_no").trim(),
                                        jArray.getJSONObject(i).getString("do_no").trim(),
                                        jArray.getJSONObject(i).getString("ticket_no").trim().contains("null")?"":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_type").trim(),
                                        jArray.getJSONObject(i).getString("action_act_qty").trim(),
                                        jArray.getJSONObject(i).getString("status").trim(),
                                        jArray.getJSONObject(i).getString("ref_id").trim(),
                                        jArray.getJSONObject(i).getString("ref_type").trim(),
                                        jArray.getJSONObject(i).getString("shipping_limit").trim(),
                                        jArray.getJSONObject(i).getString("lot_no").trim().contains("null")?"":jArray.getJSONObject(i).getString("lot_no").trim(),
                                        jArray.getJSONObject(i).getString("trucker_no").trim(),
                                        jArray.getJSONObject(i).getString("cont_no").trim(),
                                        "",
                                        jArray.getJSONObject(i).getString("do_qty").trim(),
                                        jArray.getJSONObject(i).getString("fifo_qty").trim(),
                                        jArray.getJSONObject(i).getString("location_id").trim(),
                                        String.valueOf("totalActionActQty")
                                ));
                            }

                            set_view_data(list_item);
                        }

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

    }

    private void check_leader_scan(String userid)
    {
        try {

            JSONObject json = new JSONObject();
            json.put("cmd", "LEADER/USER");
            json.put("userid",userid);

            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 user: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        if (jArray.length() == 0){
                            Toast.makeText(OutboundPickingDetail_Activity.this, "Not found user", Toast.LENGTH_SHORT).show();

                        }else {



                            scan_ticket_no_leader(ticket_no_check);



                        }

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


    }
    private void set_view_data(List<OutboundPickingDetail_item> list_item){
        int totalQty = 0;
        int totalActionActQty = 0;
        for (OutboundPickingDetail_item item : list_item) {
            int intQty = (int) Math.floor(Double.parseDouble(item.getCount_do_no()));
            totalQty = intQty;
            int intActionActQty = (int) Math.floor(Double.parseDouble(item.getAction_act_qty()));
            totalActionActQty += intActionActQty;
        }

        Log.e("ToT", "----->on loop qty detail: " + totalQty);
        Log.e("ToT", "----->on loop Action act qty detail: " + totalActionActQty);
        txt_total.setText(totalActionActQty+ "/"+totalQty);
        adapter = new Outbound_PickingDetail_Adapter( list_item , OutboundPickingDetail_Activity.this,OutboundPickingDetail_Activity.this);
        view_picking_detail.setAdapter(adapter);
    }
    private void clear_data() {

        if (txt_document_no != null) {
            txt_document_no.setText("-");
        }

        if (txt_total != null) {
            txt_total.setText("0/0");
        }

        if (map_item != null) {
            map_item.clear();
        }

        if (list_item != null) {
            list_item.clear();
        }

        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        leader_scan=false;
    }
    private void dialog_massage_not_match(){

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

        new SweetAlertDialog(OutboundPickingDetail_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(OutboundPickingDetail_Activity.this);
        customTextView.setText("Insufficient information");
        customTextView.setTextColor(Color.RED);
        customTextView.setTextSize(16);
        customTextView.setGravity(Gravity.CENTER);

        new SweetAlertDialog(OutboundPickingDetail_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(OutboundPickingDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
//                        if (clear_data){
//                            txt_part_name.setText("");
//                            txt_part_name.setBackgroundResource(R.drawable.button_background_gray);
//                            txt_part_name.setTextColor(Color.BLACK);
//                            sDialog.dismiss();
//                        }else {
//                        txt_part_name.setText("CONFIRMED");
//                        txt_part_name.setBackgroundResource(R.drawable.button_background_green);
//                        txt_part_name.setTextColor(Color.BLACK);
                        sDialog.dismiss();
//                        }

                    }

                })
                .setTitleText("INFORMATION")
                .setContentText("Operation complete!")
                .show();

        /// Clear Data
        //event_clear();

    }
    private void scan_ticket_no(String ticket_no){
        try {

            String data = str_document_no;
            Log.d(getString(R.string.tag), "======>DDDDD  : " + data);
            Log.d(getString(R.string.tag), "======>TTTTT  : " + ticket_no);
            JSONObject json = new JSONObject();
            json.put("cmd", "TICKET/OUTBOUND/PICKING");
            json.put("ticket_no", ticket_no);
            json.put("do_no", str_document_no);
            json.put("userid", Settings.getLoginUser().getId());

            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 Scan  : " + response);
                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        String status = jsonObject.getString("status");
                        String act_qty = jsonObject.getString("act_qty");
                        String qty = "0.00";

                        if(!status.equals("NG")) {
                            JSONArray jArray = new JSONArray(value);
                            for(Integer i=0;i<list_item.size();i++)
                            {
                                Double act_qty_count = 0.00;

                                for(int isub = 0; isub < jArray.length(); isub++){
                                    JSONObject obj = jArray.getJSONObject(isub);

                                    if(list_item.get(i).getParts_no().equals(obj.getString("item_id")) &&
                                            list_item.get(i).getLot_no().equals(obj.getString("tire_week")) &&
                                            list_item.get(i).getLocation_id().equals(obj.getString("location_id")))
                                    {
                                        act_qty_count = act_qty_count + Double.parseDouble(obj.getString("qty"));

                                        list_item.get(i).setTicket_no(obj.getString("ticket_no"));




                                    }
                                    else if(list_item.get(i).getParts_no().equals(obj.getString("item_id")) &&
                                            !list_item.get(i).getLot_no().equals(obj.getString("tire_week")))
                                    {

                                        if(ticket_no_check.equals("")) {
                                            ticket_no_check = ticket_no;
                                            TextView customTextView = new TextView(OutboundPickingDetail_Activity.this);
                                            customTextView.setTextColor(Color.RED);
                                            customTextView.setTextSize(16);
                                            customTextView.setText("Tire Week is different.");
                                            customTextView.setGravity(Gravity.CENTER);
                                            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                    .setTitleText("WARNING")
                                                    .setCustomView(customTextView)
                                                    .setCancelText("Back")
                                                    .showCancelButton(true)
                                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                        @Override
                                                        public void onClick(SweetAlertDialog sDialog) {
                                                            sDialog.dismiss();


                                                        }
                                                    })
                                                    .setConfirmText("Continue")
                                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                        @Override
                                                        public void onClick(SweetAlertDialog sDialog) {

                                                            sDialog.dismiss();
                                                            leader_scan();

                                                        }
                                                    })
                                                    .show();


                                        }




                                        break;


                                    }



                                }

                                qty = list_item.get(i).getQty().toString();
                                if(act_qty_count==Double.parseDouble(qty))
                                {
                                    list_item.get(i).setStatus("OK");

                                }
                                else if(act_qty_count>0.00)
                                {
                                    list_item.get(i).setStatus("NG");

                                }
                                list_item.get(i).setAction_act_qty(act_qty_count.toString());




                            }

                            set_view_data(list_item);

                        }
                        else
                        {

                            TextView customTextView = new TextView(OutboundPickingDetail_Activity.this);
                            customTextView.setText("The part numbers are different.");
                            customTextView.setTextColor(Color.RED);
                            customTextView.setTextSize(16);
                            customTextView.setGravity(Gravity.CENTER);

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

                        }










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





    }
    private void scan_ticket_no_leader(String ticket_no){
        try {

            String data = str_document_no;
            Log.d(getString(R.string.tag), "======>DDDDD  : " + data);
            Log.d(getString(R.string.tag), "======>TTTTT  : " + ticket_no);
            JSONObject json = new JSONObject();
            json.put("cmd", "TICKET/OUTBOUND/PICKING");
            json.put("ticket_no", ticket_no);
            json.put("do_no", str_document_no);
            json.put("userid", Settings.getLoginUser().getId());

            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 Scan  : " + response);
                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        String status = jsonObject.getString("status");
                        String act_qty = jsonObject.getString("act_qty");
                        String qty = "0.00";

                        if(!status.equals("NG")) {
                            JSONArray jArray = new JSONArray(value);
                            for(Integer i=0;i<list_item.size();i++)
                            {
                                Double act_qty_count = 0.00;

                                for(int isub = 0; isub < jArray.length(); isub++){
                                    JSONObject obj = jArray.getJSONObject(isub);

                                    if(list_item.get(i).getParts_no().equals(obj.getString("item_id")) &&
                                            list_item.get(i).getLot_no().equals(obj.getString("tire_week")) &&
                                            list_item.get(i).getLocation_id().equals(obj.getString("location_id")))
                                    {
                                        act_qty_count = act_qty_count + Double.parseDouble(obj.getString("qty"));

                                        list_item.get(i).setTicket_no(obj.getString("ticket_no"));




                                    }


                                }

                                qty = list_item.get(i).getQty().toString();
                                if(act_qty_count==Double.parseDouble(qty))
                                {
                                    list_item.get(i).setStatus("OK");

                                }
                                else if(act_qty_count>0.00)
                                {
                                    list_item.get(i).setStatus("NG");

                                }
                                list_item.get(i).setAction_act_qty(act_qty_count.toString());




                            }

                            set_view_data(list_item);

                        }
                        else
                        {

                            TextView customTextView = new TextView(OutboundPickingDetail_Activity.this);
                            customTextView.setText("The part numbers are different.");
                            customTextView.setTextColor(Color.RED);
                            customTextView.setTextSize(16);
                            customTextView.setGravity(Gravity.CENTER);

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

                        }





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





    }
    public  void leader_scan()
    {

        leader_scan=true;
        popupLayout5.setVisibility(VISIBLE);


    }

    public  void confirm()
    {

        int totalQty=0;
        int totalActionActQty=0;
        for (OutboundPickingDetail_item item : list_item) {
            int intQty = (int) Math.floor(Double.parseDouble(item.getQty()));
            totalQty += intQty;
            int intActionActQty = (int) Math.floor(Double.parseDouble(item.getAction_act_qty()));
            totalActionActQty += intActionActQty;
        }

        Log.e("ToT", "----->on loop qty detail: " + totalQty);
        Log.e("ToT", "----->on loop Action act qty detail: " + totalActionActQty);



        if(totalActionActQty<totalQty)
        {
            TextView customTextView = new TextView(OutboundPickingDetail_Activity.this);
            customTextView.setTextColor(Color.RED);
            customTextView.setTextSize(16);
            customTextView.setText("Quantity is insufficient.");
            customTextView.setGravity(Gravity.CENTER);
            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setCustomView(customTextView)
                    .setCancelText("Back")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();


                        }
                    })
                    .setConfirmText("Continue")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {

                            sDialog.dismiss();
                            Save_PinchList();


                        }
                    })
                    .show();

        }
        else
        {

             Save_Outbound();

        }



    }

    private  void  Save_PinchList() {

        int totalQty=0;
        int totalActionActQty=0;


        try {
            JSONObject json = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();
            for (int i = 0; i < list_item.size(); i++) {

                Double total = Double.parseDouble(list_item.get(i).getQty());
                Double act_qty = Double.parseDouble(list_item.get(i).getAction_act_qty());
                if (act_qty < total) {


                    jsonParams.put("do_no", str_document_no);
                    jsonParams.put("parts_no", list_item.get(i).getParts_no());
                    jsonParams.put("plan_qty", total.toString());
                    jsonParams.put("act_qty", act_qty.toString());
                    jsonParams.put("userid", Settings.getLoginUser().getId());
                    JSONObject jsonObj = new JSONObject(jsonParams);
                    jsonArray.put(jsonObj);


                }

                int intQty = (int) Math.floor(Double.parseDouble(list_item.get(i).getQty()));
                totalQty += intQty;
                int intActionActQty = (int) Math.floor(Double.parseDouble(list_item.get(i).getAction_act_qty()));
                totalActionActQty += intActionActQty;

            }

            ///===> Request
            json.put("cmd", "SAVE/PINCH/LIST");
            json.put("value", jsonArray);
            json.put("pick_qty", String.valueOf(totalActionActQty));
            json.put("order_qty",  String.valueOf(totalQty));

            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) {
                            Log.d("JSON", "Affected rows: " + affectedRows);
                            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("INFORMATION")
                                    .setContentText("Can't insert date.")
                                    .setConfirmText("NG")
                                    .setConfirmButtonBackgroundColor(Color.RED)
                                    .show();

                        } else {

                            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText(" INFORMATION")
                                    .setContentText("Added it to pinch list")
                                    .setConfirmText("OK")
                                    .setConfirmButtonBackgroundColor(Color.GREEN)
                                    .show();

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


                }
            }.execute();

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


        }


    }

    private  void  Save_Outbound() {

        int totalQty=0;
        int totalActionActQty=0;


        try {
            JSONObject json = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();
            for (int i = 0; i < list_item.size(); i++) {




                    jsonParams.put("do_no", str_document_no);
                    jsonParams.put("item_id", list_item.get(i).getParts_no());
                    jsonParams.put("tire_week", list_item.get(i).getLot_no());
                    jsonParams.put("location_id", list_item.get(i).getLocation_id());
                    jsonParams.put("ticket_no", list_item.get(i).getTicket_no());
                    jsonParams.put("act_qty", list_item.get(i).getAction_act_qty());
                    jsonParams.put("userid", Settings.getLoginUser().getId());
                    JSONObject jsonObj = new JSONObject(jsonParams);
                    jsonArray.put(jsonObj);




                int intQty = (int) Math.floor(Double.parseDouble(list_item.get(i).getQty()));
                totalQty += intQty;
                int intActionActQty = (int) Math.floor(Double.parseDouble(list_item.get(i).getAction_act_qty()));
                totalActionActQty += intActionActQty;

            }

            ///===> Request
            json.put("cmd", "SAVE/OUTBOUND/PICK");
            json.put("value", jsonArray);
            json.put("do_no", str_document_no);
            json.put("pick_qty", String.valueOf(totalActionActQty));
            json.put("order_qty",  String.valueOf(totalQty));

            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) {
                            Log.d("JSON", "Affected rows: " + affectedRows);
                            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("INFORMATION")
                                    .setContentText("Can't insert data.\nDuplicate data picking please check.")
                                    .setConfirmText("NG")
                                    .setConfirmButtonBackgroundColor(Color.RED)
                                    .show();

                        } else {

                            new SweetAlertDialog(OutboundPickingDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("INFORMATION")
                                    .setContentText("Operation completed!")
                                    .setConfirmText("OK")
                                    .setConfirmButtonBackgroundColor(Color.GREEN)
                                    .show();
                                     backschedule();

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


                }
            }.execute();

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


        }


    }
    private  void backschedule() {

        final Handler handler = new Handler();
        handler.postDelayed((Runnable) () -> {

            Intent intent = new Intent(OutboundPickingDetail_Activity.this, OutboundPicking_Activity.class);
            this.startActivity(intent);
            finish();
        }, 1000);


    }

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

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {

        if(data.trim().equals(""))
            return;

        if(leader_scan.equals(true))
        {


            popupLayout5.setVisibility(GONE);
            check_leader_scan(data);


        }
        else {

            if (txt_document_no.getText().toString().equals("-")) {
                txt_document_no.setText(data);
                load_data_picking_det(data);
            } else {
                scan_ticket_no(data);
            }

        }


    }

    @Override
    public void onClickRow(String id, String part_no, String tire_week, String ticket_no, String location_id, String qty, String status) {

    }

    @Override
    public void SelectionItemRow(String id, String part_no, String tire_week, String ticket_no, String location_id, String qty, String status) {


        popupLayout4.setVisibility(VISIBLE);
        if (popupLayout4.getVisibility() == VISIBLE) {

            edt_qty.setText("");

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

            //bc_tire=ticket_no
            //id = location_no

            str_id = part_no + tire_week + location_id + ticket_no;

            if(qty.equals(".00") || qty.equals(""))
            {
                qty="0";
            }
            txt_qty_total.setText("/"+qty.replace(".00",""));

            lbl_item_id = part_no;
            lbl_tire_week = tire_week;
            lbl_ticket_no = ticket_no;
            lbl_location_id = location_id;
            lbl_qty = qty;




        }


    }
}
