package com.tomas.ht_mast;

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

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.Adapter.ItemLabel_Adapter;
import com.tomas.ht_mast.ListData.LabelItem_list;
import com.tomas.ht_mast.ListData.Location_list;
import com.tomas.ht_mast.ListData.PackingStandard_list;
import com.tomas.ht_mast.lib.ActionType;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.DatetimeUtil;
import com.tomas.ht_mast.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.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class InboundDetail_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device, txt_date, txt_part_no, txt_part_name, txt_total, txt_location, txt_header, txt_order_no;
    Button btn_clear, btn_confirm;
    RecyclerView view_data;
    Bundle bundle;
    Calendar calendar;
    SimpleDateFormat date;
    String str_mode, str_sch_id, str_order, str_lot_no, str_part_no, str_part_name, str_rank, str_location, str_plan_qty, str_act_qty,
            str_inspection_flg, str_location_name, str_today, t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box, l_location, str_qc_area,
            l_part_no, str_supplier_id, str_supplier_name;
    Map<String, LabelItem_list>map_label;
    List<LabelItem_list>list_label;
    Double sum_total, f_plan_qty, f_act_qty;
    ItemLabel_Adapter label_adapter;
    boolean b_confirm;
    DecimalFormat decimalFormat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inbound_detail);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        b_confirm = false;
        decimalFormat = new DecimalFormat("#,#00");

        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_today = date.format(calendar.getTime());

        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_list>();

        sum_total = Double.valueOf(0);

        txt_header = (TextView)findViewById(R.id.txt_header);
        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());
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_today);

        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_total = (TextView) findViewById(R.id.txt_total);
        txt_location = (TextView) findViewById(R.id.txt_location);
        txt_order_no = (TextView)findViewById(R.id.txt_order_no);

        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_confirm = (Button)findViewById(R.id.btn_confirm);

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


        bundle = getIntent().getExtras();
        str_mode = Settings.getActionType().toString();
        Log.d(getString(R.string.tag), "str_mode:" + str_mode);
        if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {
            txt_header.setText("Inbound Detail");
            str_sch_id = bundle.getString("schedule_id");
            str_order = bundle.getString("order_no");
            str_part_no = bundle.getString("part_no");
            str_part_name = bundle.getString("part_name");
            str_rank = bundle.getString("rank");
            str_location = bundle.getString("location");
            str_plan_qty = bundle.getString("plan_qty");
            str_act_qty = bundle.getString("act_qty");
            str_inspection_flg = bundle.getString("inspection_flg");
            str_supplier_name = bundle.getString("supplier_name");
            str_supplier_id = bundle.getString("supplier_id");


            f_plan_qty = Double.parseDouble(str_plan_qty);
            f_act_qty = Double.parseDouble(str_act_qty);

            if (str_location.trim().equals("")){
                txt_location.setBackgroundResource(R.drawable.button_background_yellow);
            }else {
                txt_location.setHint(str_location);
            }

            txt_order_no.setText(str_order);
            txt_part_no.setText(str_part_no);
            txt_part_name.setText(str_part_name);
            txt_total.setText(String.valueOf( decimalFormat.format(Math.round(f_act_qty))+"/")+String.valueOf(decimalFormat.format(Math.round(f_plan_qty))));

            if (bundle.getBoolean("scan") == true) {
                t_box = bundle.getString("t_box");
                try {
                    Log.d(getString(R.string.tag), "JSON Label:" + Settings.getJS_label_detail().getString("id").toString());
                    map_label.put(t_box, new LabelItem_list(
                            "",
                            Settings.getJS_label_detail().getString("id").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_order_no").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_part_no").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_part_name").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_dwg_no").trim().toString(),
                            Settings.getJS_label_detail().getString("lot_no").trim().toString(),
                            String.valueOf(Math.round(Double.parseDouble(Settings.getJS_label_detail().getString("issue_qty").trim().toString()))),
                            Settings.getJS_label_detail().getString("issue_stock_qty").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_rank").trim().toString(),
                            Settings.getJS_label_detail().getString("serial_no").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_unit").trim().toString(),
                            Settings.getJS_label_detail().getString("control_unit").trim().toString(),
                            "OK",
                            Settings.getJS_label_detail().getString("lbl_supplier_id").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_supplier").trim().toString(),
                            Settings.getJS_label_detail().getString("lbl_ng").trim().toString(),
                            Settings.getJS_label_detail().getString("status").trim().toString(),
                            Settings.getJS_label_detail().getString("last_location_id").trim().toString()));


                    str_lot_no = Settings.getJS_label_detail().getString("lot_no").trim().toString();

                    View_data();
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }else {
            txt_header.setText("Inbound Manual");
            txt_order_no.setBackgroundResource(R.drawable.button_background_gray);
        }
    }

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

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

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

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

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

    private void Check_condition() {
        //check location inspection_flg งงอยู่ว่าต้องเช็คยังไง spec 47
        Log.d(getString(R.string.tag), "Check_condition:" + str_mode);
        if (map_label.size() == 0){
            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please scan label!")
                    .show();
            Unblock_button();
            return;
        }

            if (txt_location.getText().toString().equals("")){
                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Please scan location!")
                        .show();
                Unblock_button();
            }else {
                if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {
                    if (sum_total < f_plan_qty) {
                        new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Quantity is small. Proceed with the process?")
                                .setCancelText("No")
                                .showCancelButton(true)
                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sDialog) {
                                        sDialog.cancel();
                                        Unblock_button();
                                    }
                                })
                                .setConfirmText("Yes")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sDialog) {
                                        sDialog.cancel();
                                        //sent to save....
                                        Confirm_Inbound();
                                    }
                                })
                                .show();
//                    }else if (sum_total == f_plan_qty){
                    }else {
                        Confirm_Inbound();
                    }
                } else {//MANUAL
                    Confirm_Inbound();
                }
            }
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data read:" + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
            if (tokens.length == 7){//scan label
                t_order = tokens[0].trim();
                t_part = tokens[1].trim();
                t_dwg = tokens[2].trim();
                t_lot_no = tokens[3].trim();
                t_qty = tokens[4].trim();
                t_rank = tokens[5].trim();
                t_box = tokens[6].trim();//key of label
                Log.d(getString(R.string.tag), "token:" + tokens.length);

                Check_previous_label();

            }else if (tokens.length == 3){//scan location
                if (map_label.size() == 0){
                    new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Please scan label part no.!")
                            .show();
                    return;
                }

                String[] tokens_lo = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
                Log.d(getString(R.string.tag), Arrays.deepToString(tokens_lo));
                l_location = tokens_lo[0].trim();
                l_part_no = tokens_lo[1].trim();

                if (Settings.getMap_location().containsKey(l_location)){
                    Location_list list = Settings.getMap_location().get(l_location);
                    Log.d(getString(R.string.tag), "Check RANK: " + str_rank);
                    if (str_rank.trim().equals("A")||str_rank.trim().equals("B")){ //Rank : A, B only QC location
//                        if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {
                            if (list.getQc_area().trim().equals("1")) {//QC Location
                                Check_location_part();
                            } else {
                                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Limited to QC Location!")
                                        .show();
                                txt_location.setText("");
                                txt_location.setHint(str_location);
                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
                            }
//                        }else{//Inbound Manual anywhere location
//                            Check_location_part();
//                        }
                    }else {
                        if (list.getQc_area().trim().equals("0")){//QC Location
                            Check_location_part();
                        }else{
                            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Other than QC Location!")
                                    .show();
                            txt_location.setText("");
                            txt_location.setHint(str_location);
                            txt_location.setBackgroundResource(R.drawable.img_background_gray);
                        }
                    }
                }else{
                    new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Location not found!")
                            .show();
                }

            }else{
                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Invalid QR code!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_location_part() {
        String[] tokens_part = str_part_no.split("-",-1);
        Log.d(getString(R.string.tag), "PART_NO1 : "+tokens_part[1]);
        Log.d(getString(R.string.tag), "Location_PART_NO1 : "+l_part_no);

        if (l_part_no.trim().equals("")){//label location part_no == "";
            txt_location.setText(l_location);
            txt_location.setBackgroundResource(R.drawable.button_background_green);

        }else{//check math part
            if (tokens_part[1].trim().equals(l_part_no)){
                txt_location.setText(l_location);
                txt_location.setBackgroundResource(R.drawable.button_background_green);

            }else {
                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Part no. not match in location!")
                        .show();
                return;

            }
        }

        if (Settings.getMap_location().containsKey(txt_location.getText().toString().trim())){
            Location_list list = Settings.getMap_location().get(txt_location.getText().toString().trim());
            str_qc_area = list.getQc_area();
            str_location_name = list.getName();

        }else {
            txt_location.setText("");
            txt_location.setBackgroundResource(R.drawable.img_background_gray);
            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Location not found!")
                    .show();
        }

        Log.d(getString(R.string.tag), "str_qc_area :" +str_qc_area);
        Log.d(getString(R.string.tag), "str_location_name :" +str_location_name);
    }

    private void Check_previous_label() {
        Log.d(getString(R.string.tag), "str_mode :" +str_mode);
        Log.d(getString(R.string.tag), "str_part_no :" +str_part_no+"|"+t_part);
        Log.d(getString(R.string.tag), "str_mode :" +str_mode);
        if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {//Inbound Schedule
            if (str_part_no.trim().equals(t_part)) {//check part_no
                if (map_label.size() > 0){
                    if (str_lot_no.trim().equals(t_lot_no)) {//check lot_no
                        Log.d(getString(R.string.tag), "lot_no :" + str_lot_no+"="+t_lot_no);
                        if (map_label.containsKey(t_box)) {//delete label
                            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("This Box has been scanned.")
                                    .setCancelText("Delete")
                                    .showCancelButton(true)
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.cancel();
                                            map_label.remove(t_box);
                                            Log.d(getString(R.string.tag), "delete size = " + map_label.size());
                                            View_data();
                                        }
                                    })
                                    .setConfirmText("Continue")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.cancel();
                                        }
                                    })
                                    .show();
                        } else {
                            str_lot_no = t_lot_no;
                            Log.d(getString(R.string.tag), "str_part_no :" + str_part_no);

                            Double f_label_qty = Double.parseDouble(t_qty.replaceAll(",",""));
                            Double pre_total = sum_total+f_label_qty;//before add to map

                                if (sum_total >= f_plan_qty || pre_total > f_plan_qty) { //check sum_total
                                    new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("WARNING")
                                            .setContentText("The planned quantity has been exceeded")
                                            .show();
                                }else {
                                    Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                                }
                        }
                    } else {
                        new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Lot number is different")
                                .show();
                    }
                }else {
                    str_lot_no = t_lot_no;
                    Log.d(getString(R.string.tag), "str_part_no :" + str_part_no);
                    Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                }
            } else {
                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Part No. does not match Plan")
                        .show();
            }
        }else {//Inbound manual

            if (map_label.size() > 0) {
                Log.e(getString(R.string.tag), "First label: " + str_part_no+"|"+str_part_name+"|"+str_lot_no);
                if (str_part_no.trim().equals(t_part)){//check part
                    if (str_lot_no.trim().equals(t_lot_no)){ //check lot
                        if (map_label.containsKey(t_box)) {//delete label
                            Log.d(getString(R.string.tag), "t_box  containsKey:" + t_box);

                            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("This Box has been scanned.")
                                    .setCancelText("Delete")
                                    .showCancelButton(true)
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.cancel();
                                            map_label.remove(t_box);
                                            Log.d(getString(R.string.tag), "map_label size = " + map_label.size());
                                            View_data();
                                        }
                                    })
                                    .setConfirmText("Continue")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.cancel();
                                        }
                                    })
                                    .show();
                        } else {
                            Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                        }
                    }else {
                        new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Lot number is different")
                                .show();
                    }
                }else {
                    new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Part No. is different")
                            .show();
                }
            }else{//first label
                Label_Inquiry(t_order, t_part, t_lot_no, t_box);
            }
        }
    }

    private void Label_Inquiry(String order_no, String parts_no, String lot_no, String box) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/LABEL/INQUIRY");
            json.put("order_no", order_no);
            json.put("parts_no", parts_no);
            json.put("lot_no", lot_no);
            json.put("serial_no", box);

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        if (jArray.length() == 0){
                            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Label not found!")
                                    .show();
                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            Log.d(getString(R.string.tag),"t_box put: "+ String.valueOf(t_box));
                            if (status_label.trim().equals("1") || status_label.trim().equals("3")) {
                                map_label.put(t_box, new LabelItem_list(
                                        "",
                                        jArray.getJSONObject(0).getString("id").trim(),
                                        jArray.getJSONObject(0).getString("lbl_order_no").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_no").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_name").trim(),
                                        jArray.getJSONObject(0).getString("lbl_dwg_no").trim(),
                                        jArray.getJSONObject(0).getString("lot_no").trim(),
                                        String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("issue_qty").trim()))),
                                        jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("lbl_rank").trim(),
                                        jArray.getJSONObject(0).getString("serial_no").trim(),
                                        jArray.getJSONObject(0).getString("lbl_unit").trim(),
                                        jArray.getJSONObject(0).getString("control_unit").trim(),
                                        "OK",
                                        jArray.getJSONObject(0).getString("lbl_supplier_id").trim(),
                                        jArray.getJSONObject(0).getString("lbl_supplier").trim(),
                                        jArray.getJSONObject(0).getString("lbl_ng").trim(),
                                        jArray.getJSONObject(0).getString("status").trim(),
                                        jArray.getJSONObject(0).getString("last_location_id").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_id").trim()));


                                if (str_mode.trim().equals(ActionType.Type.INBOUND_MANUAL.toString()) && map_label.size() == 1) {
                                    str_part_no = jArray.getJSONObject(0).getString("lbl_part_no").trim();
                                    str_part_name =  jArray.getJSONObject(0).getString("lbl_part_name").trim();
                                    str_lot_no =  jArray.getJSONObject(0).getString("lot_no").trim();
                                    str_rank = jArray.getJSONObject(0).getString("lbl_rank").trim();
                                    Log.d(getString(R.string.tag), "RANK: " + str_rank);
                                    if (str_rank.trim().equals("A")||str_rank.trim().equals("B")){
                                        str_inspection_flg = "1";
                                    }else {
                                        str_inspection_flg = "0";
                                    }
                                    Log.d(getString(R.string.tag), "str_inspection_flg: " + str_inspection_flg);
                                }
                                View_data();
                            }else {
                                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Invalid Label!")
                                        .show();
                            }
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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



    private void View_data() {
        list_label.clear();
        sum_total = Double.valueOf(0);
        int no = 0;
        Log.d(getString(R.string.tag),"mapItem"+ String.valueOf(map_label.size()));
        for (String key : map_label.keySet()){
           no = (no + 1);
            LabelItem_list item = map_label.get(key);
            list_label.add(new LabelItem_list(
                    String.valueOf(no),
                    item.getLabel_id(),
                    item.getOrder_no(),
                    item.getPart_no(),
                    item.getPart_name(),
                    item.getDwg_no(),
                    item.getLot_no(),
                    item.getIssue_qty(),
                    item.getIssue_stock_qty(),
                    item.getRank(),
                    item.getBox_no(),
                    item.getUnit(),
                    item.getControl_unit(),
                    item.getStatus(),
                    item.getLbl_supplier_id(),
                    item.getLbl_supplier(),
                    item.getLbl_ng(),
                    item.getStatus_label(),
                    item.getLast_location_id()));

            Double qty = Double.parseDouble(item.getIssue_qty());
            sum_total = (sum_total + qty);
            Log.d(getString(R.string.tag),"SUM "+ String.valueOf(sum_total));
        }

        label_adapter = new ItemLabel_Adapter(list_label, this);
        view_data.setAdapter(label_adapter);
        Log.d(getString(R.string.tag), "set adapter");

//        if (map_label.size() == 0){
//            btn_confirm.setEnabled(false);
//            btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
//            btn_clear.setEnabled(false);
//            btn_clear.setBackgroundResource(R.drawable.button_background_gray);
//        }else {
//            btn_confirm.setEnabled(true);
//            btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
//            btn_clear.setEnabled(true);
//            btn_clear.setBackgroundResource(R.drawable.button_background_yellow);
//        }

        if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {//Inbound Schedule
            //+act_qty
            Log.d(getString(R.string.tag), "sum_total : "+sum_total+"+"+f_act_qty);
            sum_total = (sum_total + f_act_qty);
            Log.d(getString(R.string.tag), "sum_total = "+sum_total);
            txt_total.setText(decimalFormat.format(Math.round(sum_total)  )+ "/" +decimalFormat.format(Math.round(f_plan_qty)));
        }else {
            txt_total.setText(String.valueOf(decimalFormat.format(Math.round(sum_total))));
            txt_part_name.setText(str_part_name);
            txt_part_no.setText(str_part_no);

            if (map_label.size() == 0){
                txt_part_no.setText("");
                txt_part_name.setText("");
                str_part_no = "";
                str_part_name = "";
                str_lot_no = "";
            }
        }
    }

    private void Confirm_Inbound() {
        Log.d(getString(R.string.tag),"Confirm_Inbound "+ str_mode+"/"+str_inspection_flg);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {
                json.put("cmd", "INBOUND/SCHEDULE/DETAIL/CONFIRM");
            }else {
                json.put("cmd", "INBOUND/MANUAL/DETAIL/CONFIRM");
            }

            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()){
                LabelItem_list item = map_label.get(key);
                jsonParams.put("item_id", txt_part_no.getText().toString().trim());
                jsonParams.put("item_name", txt_part_name.getText().toString().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());

                if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {
                    jsonParams.put("ref_sch_id", str_sch_id);
                    jsonParams.put("inspection_flg", str_inspection_flg);

                }else {
                    if (str_qc_area.trim().equals("1")){
                        jsonParams.put("inspection_flg", "1");
                    }else {
                        jsonParams.put("inspection_flg", "0");
                    }
                }
                jsonParams.put("status",  "1");
                jsonParams.put("slip_divide", "3");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("qty",item.getIssue_stock_qty());
                jsonParams.put("package_qty",item.getIssue_qty());
                jsonParams.put("location_id", txt_location.getText().toString().trim());
                jsonParams.put("location_name", str_location_name.trim().equals("null") ? "" : str_location_name);
                jsonParams.put("supplier_id", item.getLbl_supplier_id().trim().equals("null") ? "" : item.getLbl_supplier_id().trim());
                jsonParams.put("supplier_name", item.getLbl_supplier().trim().equals("null") ? "" : item.getLbl_supplier().trim());
                jsonParams.put("package_id", item.getUnit());
                jsonParams.put("unit_qty", item.getControl_unit());
                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("ng", item.getLbl_ng());

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }
            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) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Log.d(getString(R.string.tag),"response"+ response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            //SUCCESS
                            if (str_mode.trim().equals(ActionType.Type.INBOUND_MANUAL.toString())) {
                                new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                        .setTitleText("SUCCESS")
                                        .setContentText("Insert data completed")
                                        .show();
                                txt_part_name.setText("");
                                txt_part_no.setText("");
                                txt_location.setText("");
                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
                                txt_total.setText("0");
                                map_label.clear();
                                View_data();
                                Unblock_button();
                            }else {
                                finish();
                            }
                        }else {
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                            Unblock_button();
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                        Unblock_button();
                    }
                }
            }.execute();
        }catch (Exception e) {
            new SweetAlertDialog(InboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
            Unblock_button();
        }
    }

    @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 P3:
                    Clear_layout();

                    break;

                case P4://confirm
                    if (b_confirm == false) {
                        Block_button();
                        Check_condition();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    private void Clear_layout() {
        b_confirm = false;
        map_label.clear();
        txt_location.setText("");
        txt_location.setBackgroundResource(R.drawable.img_background_gray);
        View_data();
    }
}