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.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.Adapter.StocktakingLabel_Adapter;
import com.tomas.ht_mast.ListData.LabelItem_list;
import com.tomas.ht_mast.ListData.LabelItem_out_sh_list;
import com.tomas.ht_mast.ListData.Supplier_list;
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.Utils;

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

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 StocktakingLabel_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device, txt_location;
    Button btn_clear, btn_confirm;
    RecyclerView view_data;
    String str_location;
    Map<String, LabelItem_list> map_label;
    Calendar calendar;
    boolean b_confirm;
    List<LabelItem_list> list_label;
    StocktakingLabel_Adapter label_adapter;

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

        b_confirm = false;
        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_list>();
        calendar = Calendar.getInstance();

        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_location = (TextView) findViewById(R.id.txt_location);

        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());

    }


    @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();
                    UpdateStocktaking();
                }
                break;
        }
    }

    private void Clear_layout() {
        Unblock_button();
        map_label.clear();
        txt_location.setText("");
        str_location = "";
        View_data();
    }

    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("") || b_confirm == true)
            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){
                if (txt_location.getText().toString().trim().equals("")){
                    showWarning("Please scan location!!");

                }else {
                    Label_Inquiry(tokens[0].trim(), tokens[1].trim(), tokens[3].trim(), tokens[6].trim());
                }
            }else if (tokens.length == 3){//scan location
                if (txt_location.getText().toString().trim().equals("")||map_label.size() == 0) {
                    str_location = tokens[0].trim();
                    if (Settings.getMap_location().containsKey(str_location)){
                        txt_location.setText(str_location);

                    }else {
                        showWarning("Location not found!!");
                    }
                }else {
                    showWarning("Can't change location!!");
                }
            }else {
                showWarning("Invalid QR code!!");
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Label_Inquiry(String order_no, String parts_no, String lot_no, String box) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            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(StocktakingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Label not found!")
                                    .show();
                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            String last_location = jArray.getJSONObject(0).getString("last_location_id").trim();
                            String id_label = jArray.getJSONObject(0).getString("id").trim();
                            Log.d(getString(R.string.tag), "response: " + id_label+" / "+last_location+" / "+status_label);
                            //check duplicate label in map
                            if (map_label.containsKey(id_label)) {
                                new SweetAlertDialog(StocktakingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("This Label has been scanned.")
                                        .setCancelText(" Delete")
                                        .showCancelButton(true)
                                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sDialog) {
                                                sDialog.cancel();
                                                map_label.remove(id_label);
                                                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 {
//                                if (status_label.trim().equals("2") || status_label.trim().equals("5")) {//check status label
//                                    if (last_location.trim().equals(txt_location.getText().toString().trim())) {//check location
                                        map_label.put(jArray.getJSONObject(0).getString("id").trim(), 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(),
                                                "",
                                                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(),
                                                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()));

                                        View_data();
//                                    } else {
//                                        new SweetAlertDialog(StocktakingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                                .setTitleText("WARNING")
//                                                .setContentText("location not match!")
//                                                .show();
//                                    }
//                                } else {
//                                    new SweetAlertDialog(StocktakingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                            .setTitleText("WARNING")
//                                            .setContentText("Invalid Label status!")
//                                            .show();
//                                }
                            }
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(StocktakingLabel_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void View_data() {
        list_label.clear();
        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()));//location

            Log.d(getString(R.string.tag),"getLabel_id"+ String.valueOf(item.getLabel_id()));
        }
        label_adapter = new StocktakingLabel_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);
        }else {
            if (b_confirm == true){
                btn_confirm.setEnabled(false);
                btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
            }else {
                btn_confirm.setEnabled(true);
                btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
            }
        }
    }

    private void UpdateStocktaking() {
        if (map_label.size() == 0)
            return;

        Block_button();
        calendar = Calendar.getInstance();
        SimpleDateFormat date_time = new SimpleDateFormat("yyyyMM");
        String str_date = date_time.format(calendar.getTime());
        Log.d(getString(R.string.tag), "str_date: " + str_date);

        Log.d(getString(R.string.tag), "UpdateStocktaking");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "add");

            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()) {
                LabelItem_list item = map_label.get(key);
                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("serial_no", item.getBox_no());
                jsonParams.put("item_id", item.getPart_no());
//                jsonParams.put("location_id", item.getLast_location_id());
                jsonParams.put("location_id", txt_location.getText().toString().trim());
                jsonParams.put("lot_no", item.getLot_no());
                jsonParams.put("taking_month", str_date);
                jsonParams.put("st_qty", item.getIssue_stock_qty());
                jsonParams.put("qty", item.getIssue_stock_qty());
                jsonParams.put("control_unit", item.getUnit());
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
                json.put("stock_datas", jsonArray);
            }

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

                    try {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0 || response.trim().equals("")){
                            Unblock_button();
                            showError("Can't register stocktaking data!!");
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                try {
                                    String id_label = jArray.getJSONObject(i).getString("label_id");
                                    String status = jArray.getJSONObject(i).getString("status");
                                    int affected_rows = jArray.getJSONObject(i).getInt("affected_rows");

                                    Log.d(getString(R.string.tag), "jArray: " + id_label + "|" + status + "|" + affected_rows);

                                    LabelItem_list item = map_label.get(id_label);
                                    if (status.trim().equals("success") && affected_rows == 1) {
                                        item.setStatus("OK");
                                    } else {
                                        item.setStatus("NG");
                                    }
                                    map_label.put(id_label, item);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            View_data();
                            showSuccess("Insert stocktaking completed!!");
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        e.printStackTrace();
                    }
                }
            }.execute();

        } catch (Exception e) {
            Unblock_button();
            Log.e(getString(R.string.tag), e.getMessage());
        }
    }

    @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();
                        UpdateStocktaking();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}