package com.tomas.ht_ydt;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_ydt.ListData.LabelItem_list;
import com.tomas.ht_ydt.lib.ActionType;
import com.tomas.ht_ydt.lib.KeyMapping;
import com.tomas.ht_ydt.lib.Scanner;
import com.tomas.ht_ydt.lib.Settings;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;
import com.tomas.ht_ydt.lib.common.Utils;

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

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class QCDetail_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device,txt_part_no, txt_part_name, txt_lot_no, txt_act_qty, txt_plan_qty, txt_location;
    ImageButton imb_back;
    Button btn_clear, btn_confirm;
    Bundle bundle;
    String  s_location, s_list_item, key_label, l_part_no, l_lot_no, l_serial, l_label_id,
    str_sch_id, str_order, str_part_no, str_part_name, str_dest_location, str_ref_id, str_product_no, str_plan_qty, str_act_qty, str_lot_no,
            str_last_location, str_unit_qty;
    boolean b_confirm;
    Map<String, LabelItem_list> map_label;

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

        b_confirm = false;

        map_label = new LinkedHashMap<>();

        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_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_act_qty = (TextView) findViewById(R.id.txt_act_qty);
        txt_plan_qty = (TextView) findViewById(R.id.txt_plan_qty);
        txt_location = (TextView) findViewById(R.id.txt_location);

        imb_back = (ImageButton) findViewById(R.id.imb_back);
        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
        btn_confirm.setEnabled(false);


        bundle = getIntent().getExtras();

        str_sch_id = bundle.getString("schedule_id");
        str_ref_id = bundle.getString("ref_id");
        str_product_no = bundle.getString("product_no");
        str_order = bundle.getString("order_no");
        str_part_no = bundle.getString("part_no");
        str_part_name = bundle.getString("part_name");
        str_dest_location = bundle.getString("dest_location_id");
        str_plan_qty = bundle.getString("plan_qty");
        str_act_qty = bundle.getString("act_qty");
        str_unit_qty = bundle.getString("unit_qty");

        txt_part_no.setText(str_part_no);
        txt_part_name.setText(str_part_name);
        txt_location.setText(str_dest_location);
        txt_plan_qty.setText("/ "+str_plan_qty+"  "+ str_unit_qty);

    }

    @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 (map_label.size() == 0 || txt_location.getText().toString().equals("")){
                    return;
                }else {
                    if (b_confirm == false) {
                        Block_button();
                        Check_Move_Location();
                    }
                }
                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);
    }

    @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 == 2){//scan location [LOCATION CODE] │[ITEM CODE1],[ITEM CODE2],…
                if (map_label.size() > 0){
                    s_location = tokens[0].trim();
                    s_list_item = tokens[1].trim();

                    if (Settings.getMap_location().containsKey(s_location)) {
                        txt_location.setText(s_location);
                        txt_location.setBackgroundResource(R.drawable.button_background_ok);

                    }else {
                        showWarning("Location not found!");
                    }
                }else {
                    showWarning("Please scan label!");
//                    return;
                }

            }else if (tokens.length == 4){//scab label [PART CODE] | [LOT] | [SERIAL NO] | [LABEL ID]
                key_label = data.trim();
                l_part_no = tokens[0].trim();
                l_lot_no = tokens[1].trim();
                l_serial = tokens[2].trim();
                l_label_id = tokens[3].trim();

                if (str_part_no.trim().equals(l_part_no)){
                    if (map_label.size() > 0){
                        Check_Map_Label();
                    }else {
                        Check_Label();
                    }

                }else {
                    showWarning("Parts No. not match!");
//                    return;
                }

            }else {
                showWarning("Invalid QR code!");
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        }catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Check_Map_Label() {
        Log.d(getString(R.string.tag), "KEY : " + key_label);
        if (map_label.containsKey(key_label)){
            SweetAlertDialog d = new SweetAlertDialog(QCDetail_Activity.this, SweetAlertDialog.WARNING_TYPE);
            d.setCancelable(false);
            d.setTitleText("WARNING");
            d.setContentText("This label has been scanned.");
            d.setCancelText("Delete");
            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sd) {
                    sd.dismiss();
                    map_label.remove(key_label);
                    Log.d(getString(R.string.tag), "delete size = " + map_label.size());
                    Summary_data_scan();
                }
            });
            d.setConfirmText("Continue");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sd) {
                    sd.dismiss();
                }
            });
            d.show();

        }else {
            Check_Label();
        }
    }

    private void Check_Label() {
        Log.d(getString(R.string.tag), "Check_Label : " + key_label+": "+l_label_id+" "+l_part_no+" "+l_lot_no+" "+l_serial);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("id", l_label_id);
            json.put("parts_no", l_part_no);
            json.put("lot_no", l_lot_no);
            json.put("serial_no", l_serial);

            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){
                            showWarning("Label not found!");

                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            Log.d(getString(R.string.tag), "status_label: " + status_label);
                            if (status_label.trim().equals("2")) {
                                //check order
                                String order_no =  jArray.getJSONObject(0).getString("lbl_order_no").trim();
                                if (str_order.trim().equalsIgnoreCase(order_no)) {

                                    str_lot_no = jArray.getJSONObject(0).getString("lot_no").trim();

                                    map_label.put(key_label, new LabelItem_list(
                                            "",
                                            jArray.getJSONObject(0).getString("id").trim(),
                                            str_lot_no,
                                            jArray.getJSONObject(0).getString("serial_no").trim(),
                                            jArray.getJSONObject(0).getString("status").trim(),
                                            jArray.getJSONObject(0).getString("issue_qty").trim(),
                                            jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                            jArray.getJSONObject(0).getString("act_stock_qty").trim(),
                                            jArray.getJSONObject(0).getString("control_unit").trim(),
                                            jArray.getJSONObject(0).getString("lbl_supplier_id").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("lbl_supplier_id").trim(),
                                            jArray.getJSONObject(0).getString("lbl_supplier").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("lbl_supplier").trim(),
                                            str_part_no,
                                            str_part_name,
                                            jArray.getJSONObject(0).getString("lbl_unit").trim(),
                                            jArray.getJSONObject(0).getString("lbl_ng").trim(),
                                            jArray.getJSONObject(0).getString("last_location_id").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_id").trim(),
                                            jArray.getJSONObject(0).getString("last_location_name").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_name").trim(),
                                            "",
                                            "",
                                            jArray.getJSONObject(0).getString("lbl_order_no").trim()));


                                    txt_lot_no.setText(str_lot_no);
                                    Summary_data_scan();
                                }else {
                                    showWarning("Label doesn't match order_no.! : "+str_order);
                                }
                            }else {
                                showWarning("Invalid Label Status! : "+status_label);
                            }
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());

                    }
                }
            }.execute();

        }catch (JSONException e) {
            showError(e.getMessage());
        }
    }

    private void Summary_data_scan() {
        Double sum_total = 0.0;
        for (String key : map_label.keySet()){
            LabelItem_list item = map_label.get(key);
            String issue_stock_qty = item.getIssue_stock_qty();
            Double qty = Double.parseDouble(issue_stock_qty);

                sum_total = (sum_total + qty);
        }
        txt_act_qty.setText(String.format("%.2f",sum_total));

        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
        btn_confirm.setEnabled(true);
    }


    private void Check_Move_Location() {
        Log.d(getString(R.string.tag), "MoveAllLocation: " );
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QC/CHANGE_LOCATION/UPDATE");

                // Inbound
            JSONArray jArray_in = new JSONArray();
            Map<String, String> jsonParams_in = new HashMap<>();
            for (String key : map_label.keySet()) {
                LabelItem_list item = map_label.get(key);
                String last_location = item.getLast_location_id();
                String new_location = txt_location.getText().toString().trim();
                Log.d(getString(R.string.tag), "location: " + last_location+"/"+new_location);

                if (!last_location.trim().equals(new_location)) {
                    jsonParams_in.put("ref_sch_id", "");
                    jsonParams_in.put("item_id", item.getLbl_part_no());
                    jsonParams_in.put("item_name", item.getLbl_part_name());
                    jsonParams_in.put("supplier_id", item.getLbl_supplier_id());
                    jsonParams_in.put("supplier_name", item.getLbl_supplier());
                    jsonParams_in.put("package_id",item.getLbl_unit());
                    jsonParams_in.put("unit_qty", item.getControl_unit());
                    jsonParams_in.put("package_qty", item.getIssue_qty());
                    jsonParams_in.put("lot_no", item.getLot_no());
                    jsonParams_in.put("qty", item.getIssue_stock_qty());
                    jsonParams_in.put("location_id", new_location);
                    jsonParams_in.put("location_name", Settings.getMap_location().get(new_location).getName());
                    jsonParams_in.put("label_id", item.getLabel_id());
                    jsonParams_in.put("inspection_flg", "0");
                    jsonParams_in.put("status", "1"); // STORE_IN(1)
                    jsonParams_in.put("slip_divide", "3");
                    jsonParams_in.put("create_user_id", Settings.getLoginUser().getId());
                    JSONObject jsonObject = new JSONObject(jsonParams_in);
                    jArray_in.put(jsonObject);
                }
            }
            json.put("inbound_data", jArray_in);

                // Outbound
            JSONArray jArray_out = new JSONArray();
            Map<String, String> jsonParams_out = new HashMap<>();
            for (String key : map_label.keySet()) {
                LabelItem_list item = map_label.get(key);
                String last_location = item.getLast_location_id();

                if (!last_location.trim().equalsIgnoreCase(txt_location.getText().toString().trim())) {
                    jsonParams_out.put("item_id", item.getLbl_part_no());
                    jsonParams_out.put("item_name", item.getLbl_part_name());
                    jsonParams_out.put("customer_id", item.getLbl_supplier_id());
                    jsonParams_out.put("customer_name", item.getLbl_supplier());
                    jsonParams_out.put("package_id",item.getLbl_unit());
                    jsonParams_out.put("unit_qty", item.getControl_unit());
                    jsonParams_out.put("package_qty", item.getIssue_qty());
                    jsonParams_out.put("lot_no", item.getLot_no());
                    jsonParams_out.put("qty", item.getIssue_stock_qty());
                    jsonParams_out.put("location_id", item.getLast_location_id());
                    jsonParams_out.put("location_name",item.getLocation_name());
                    jsonParams_out.put("label_id", item.getLabel_id());
                    jsonParams_out.put("status", "2"); // STORE_IN(1)
                    jsonParams_out.put("slip_divide", "4");
                    jsonParams_out.put("create_user_id", Settings.getLoginUser().getId());
                    JSONObject jsonObject = new JSONObject(jsonParams_out);
                    jArray_out.put(jsonObject);
                }
            }
            json.put("outbound_data", jArray_out);

            if (jArray_out.length() == 0 || jArray_in.length() == 0){
                finish();

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

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");

                            if (status.equals("success") && jsonObject.getInt("affected_rows") == (jArray_in.length()+jArray_out.length())) {
                                Log.d(getString(R.string.tag), "new label: " + response);
                                Check_Act_Qty();
                            } else {
                                showError("QC Change location failed[" + jsonObject.getString("error") + "]!!");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }.execute();
            }

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

    private void Check_Act_Qty() {
        String status = "";
        Double total = 0.0, act_qty = 0.0, act_scan_qty = 0.0, plan_qty = 0.0;
        plan_qty = Double.parseDouble(str_plan_qty);
        act_qty = Double.parseDouble(str_act_qty);
        act_scan_qty = Double.parseDouble(txt_act_qty.getText().toString().trim());
        total = (act_qty + act_scan_qty);
        Log.d(getString(R.string.tag), "total:" + total);

        if (total < plan_qty){
            status = "WORKING";

        }else {
            status = "COMPLETED";
        }

        Update_QC_Schedule(total, status);

    }

    private void Update_QC_Schedule(Double action_act_qty, String status) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QC/SCHEDULE/UPDATE");
            json.put("action_act_qty", action_act_qty);
            json.put("id",str_sch_id);
            json.put("status",status);
            json.put("action_user_id",Settings.getLoginUser().getId());
            json.put("action_user_name",Settings.getLoginUser().getName());

            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),"Inbound response"+ response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            finish();

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            showError(error);

                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        showError(e.getMessage());
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            showError(e.getMessage());
        }

    }




    private void Clear_layout() {
        Unblock_button();
        b_confirm = false;
        map_label.clear();
        txt_lot_no.setText("");
        txt_act_qty.setText("");
        txt_location.setText(str_dest_location);
        txt_location.setBackgroundResource(R.drawable.button_background_menu_);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
        btn_confirm.setEnabled(false);

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    imb_back.performClick();
                    break;

                case P3:
                    btn_clear.performClick();
                    break;
                case P4:
                    btn_confirm.performClick();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}