package kr.co.compcarecompany.Fragment.Main;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
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.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.Company.CompanyData;
import kr.co.compcarecompany.Data.Company.WorkData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ServiceListAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.CustomView.ServiceDetailDialog;

@SuppressLint("ValidFragment")
public class Service_List_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView service_registrationTV, service_stateTV;
    private RecyclerView service_listRV;
    private ArrayItem<WorkData> workArray;
    private ServiceListAdapter workAdapter;
    private CompanyData companyData;
    private LinearLayoutManager layoutManager;
    private ProgressBar servicePB;
    private int lastIndex = 0, limitCount = 10, count = 0;

    String[] arr_str = new String[]{"전체", "접수", "완료"};
    String sortText = "전체";
    String[] sortType = new String[]{"", "C", "M"};
    String sort = "";


    @SuppressLint("ValidFragment")
    public Service_List_Fragment(Handler handler, CompanyData companyData) {
        this.handler = handler;
        this.companyData = companyData;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_service_list, container, false);

        service_registrationTV = v.findViewById(R.id.service_registrationTV);
        service_listRV = v.findViewById(R.id.service_listRV);
        service_stateTV = v.findViewById(R.id.service_stateTV);
        servicePB = v.findViewById(R.id.servicePB);

        workAdapter = new ServiceListAdapter(getContext(), new ServiceListAdapter.clickListener() {
            @Override
            public void clickBtn(Bundle bundle) {
                ServiceDetailDialog dialog = new ServiceDetailDialog(getContext(), handler, bundle.getString("wo_idx"));
                dialog.show();
            }
        }, new ServiceListAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore(int position) {
                if (count == limitCount) {
                    lastIndex += limitCount;
                    Get_Service_List();
                }
            }
        });

        layoutManager = new LinearLayoutManager(getContext());
        service_listRV.setLayoutManager(layoutManager);
        service_listRV.setAdapter(workAdapter);

        init_Handler();
        init_Listener();
        Get_Service_List();

        return v;
    }

    void Get_Service_List() {

        servicePB.setVisibility(View.VISIBLE);

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("pt_idx", fa.userItem.getArrayitem().getPtIdx());
        data.put("type", sort);
        data.put("off_set", lastIndex+"");
        data.put("limit", limitCount+"");
        new ApiClient(data, "proc_admin_get_work_list2", handler);
    }

    void init_Listener() {

        //서비스 상태 조건 검색 클릭  리스너
        service_stateTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int sortWhich = 0;
                for (int i = 0; i < arr_str.length; i++)
                    if (sortText.equals(arr_str[i]))
                        sortWhich = i;

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                alertDialogBuilder.setSingleChoiceItems(arr_str, sortWhich, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        service_stateTV.setText("서비스일정(" + arr_str[which] + ")▼");
                        sortText = arr_str[which];
                        sort = sortType[which];
                        lastIndex = 0;
                        count = 0;
                        Get_Service_List();
                        dialog.dismiss();
                    }
                });
                alertDialogBuilder.show();
            }
        });

        //서비스 접수 클릭 리스너
        service_registrationTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "서비스 접수");
                intent.putExtra("type", "service_registration");
                intent.putExtra("value1", companyData);
                startActivity(intent);
            }
        });
    }

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

                if (msg.what == 1) {
                    String url = msg.getData().getString("url");
                    if (url.equals("proc_admin_get_work_list2")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        workArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<WorkData>>() {
                        }.getType());

                        //모니터링 데이터를 정상적으로 가져왔을 때
                        if (workArray.isSuccess()) {

                            count = workArray.size();
                            if (lastIndex != 0) {
                                workAdapter.addItemMore(workArray.getArrayitem());
                            } else {
                                workAdapter.addItem(workArray.getArrayitem());
                            }

                        } else {
                            workAdapter.clearItem();
                        }

                    } else {
                        Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    }
                    servicePB.setVisibility(View.GONE);
                }
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        Get_Service_List();
    }
}