package kr.co.compcareworker.Util.CustomView;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

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

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.PlanDetail.InvoiceData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.TransactionRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.MyOnItemClick;

public class TransactionDialog extends Dialog implements MyOnItemClick {

    Context context;
    TransactionRecyclerAdapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayItem<InvoiceData> transaction_array;
    InvoiceData transaction_data;
    Handler hdr;

    ProgressBar transaction_progress;
    EditText transaction_search_nameET;
    Button transaction_searchBtn;
    RecyclerView transactionRV;

    FragmentActivity fa;

    private TransactionDialogListener transactionDialogListener;

    public interface TransactionDialogListener {
        void clickBtn(HashMap<String, String> data);
    }

    public TransactionDialog(Context context, TransactionDialogListener transactionDialogListener) {
        super(context);
        this.context = context;
        this.transactionDialogListener = transactionDialogListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dlg_transaction);

        transaction_progress = findViewById(R.id.transaction_progress);
        transaction_search_nameET = findViewById(R.id.transaction_search_nameET);
        transaction_searchBtn = findViewById(R.id.transaction_searchBtn);
        transactionRV = findViewById(R.id.transactionRV);

        transaction_searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                transaction_progress.setVisibility(View.VISIBLE);

                HashMap<String, String> data = new HashMap();
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("cu_name", transaction_search_nameET.getText().toString());
                new ApiClient(data, "proc_invoice_view", hdr);

                transaction_search_nameET.getText().clear();
            }
        });

        init_Handler();
        Get_Product();
    }

    void Get_Product() {

        transaction_progress.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        new ApiClient(data, "proc_invoice_view", hdr);
    }

    void Set_Content() {

        adapter = new TransactionRecyclerAdapter(context, hdr, this::onClick);
        layoutManager = new LinearLayoutManager(getContext());
        transactionRV.setLayoutManager(layoutManager);
        adapter.addItem(transaction_array.getArrayitem());
        transactionRV.setAdapter(adapter);

        transaction_progress.setVisibility(View.GONE);

    }

    //리스트 클릭 시
    @Override
    public void onClick(Bundle value) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
        dialogBuilder.setTitle("품목 추가");
        dialogBuilder.setMessage("선택한 거래내역을 추가하시겠습니까?");
        dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {

                transaction_progress.setVisibility(View.VISIBLE);
                transaction_progress.bringToFront();

                HashMap<String, String> data = new HashMap();
                data.put("iv_idx", value.getString("iv_idx"));

                transactionDialogListener.clickBtn(data);

                hdr.postDelayed(new Runnable() {
                    public void run() {
                        transaction_progress.setVisibility(View.GONE);
                    }
                }, 500);
                dialog.dismiss();
            }
        });
        dialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialogBuilder.show();
    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    String url = msg.getData().getString("url");
                    if (url.equals("proc_invoice_view")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        transaction_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<InvoiceData>>() {
                        }.getType());

                        if (transaction_array.isSuccess()) {
                            if (transaction_array.size() > 0) {

                                for (int i = 0; i < transaction_array.size(); i++) {
                                    transaction_data = transaction_array.getArrayitem().get(i);
                                }
                            }

                            Set_Content();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            dismiss();
                        }
                    }
                }
            }
        };
    }
}