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.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.R;
import kr.co.compcarecompany.Util.Adapter.CompanyManagementAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;
import kr.co.compcarecompany.Util.CustomView.AddPlaceDialog;

import static kr.co.compcarecompany.Activity.ActivityBasic.userItem;

public class Company_Management_Fragment extends Fragment {

    private Handler handler;
    private FragmentActivity fa;

    private TextView cp_manage_pt_nameTV, cp_manage_pt_ceoTV, cp_manage_pt_codeTV, cp_manage_add_companyTV;
    private RecyclerView cp_manage_cp_listRV;
    private String ag_idx, pt_idx;
    private ArrayItem<CompanyData> companyItems;
    private ProgressBar cp_managePB;

    @SuppressLint("ValidFragment")
    public Company_Management_Fragment(Handler handler) {
        this.handler = handler;
    }

    @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_company_management, container, false);

        ag_idx = fa.userItem.getArrayitem().getAgIdx();
        pt_idx = fa.userItem.getArrayitem().getPtIdx();
        cp_manage_pt_nameTV = v.findViewById(R.id.cp_manage_pt_nameTV);
        cp_manage_pt_ceoTV = v.findViewById(R.id.cp_manage_pt_ceoTV);
        cp_manage_pt_codeTV = v.findViewById(R.id.cp_manage_pt_codeTV);
        cp_manage_add_companyTV = v.findViewById(R.id.cp_manage_add_companyTV);
        cp_manage_cp_listRV = v.findViewById(R.id.cp_manage_cp_listRV);
        cp_managePB = v.findViewById(R.id.cp_managePB);

        init_Listener();
        init_Handler();
        Get_partner();

        return v;
    }

    void Get_partner() {
        cp_managePB.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", ag_idx);
        data.put("pt_idx", pt_idx);
        data.put("type", "COMPANY");
        new ApiClient(data, "proc_admin_partner_view", handler);
    }

    void Set_Content() {

        cp_manage_pt_nameTV.setText(companyItems.get(0).getPtName());
        cp_manage_pt_ceoTV.setText(companyItems.get(0).getPtCeo());
        cp_manage_pt_codeTV.setText(companyItems.get(0).getPtCode());

        CompanyManagementAdapter cp_adapter = new CompanyManagementAdapter(getContext(), handler, new CompanyManagementAdapter.cp_modifyClickListener() {
            @Override
            public void clickBtn() {
                Get_partner();
            }
        }, new CompanyManagementAdapter.cp_delClickListener() {
            @Override
            public void clickBtn(String cp_idx) {

                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("해당 지점을 삭제하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        //해당 지점에 등록된 기기도 같이 바꿔주기
                        HashMap<String, String> data = new HashMap<>();
                        data.put("ag_idx", ag_idx);
                        data.put("cp_idx", cp_idx);
                        new ApiClient(data, "proc_admin_company_delete", handler);
                        dialog.dismiss();
                    }
                });
                dialogBuilder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        }, new CompanyManagementAdapter.airline_modifyClickListener() {
            @Override
            public void clickBtn() {
                //해당 에어라인에 연결된 기기도 같이 바꿔주기
                Get_partner();
            }
        });
        cp_adapter.addItem(companyItems.getArrayitem());
        cp_manage_cp_listRV.setAdapter(cp_adapter);

    }

    void init_Listener() {

        //장소추가 클릭 리스너
        cp_manage_add_companyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AddPlaceDialog dialog = new AddPlaceDialog(getContext(), handler, ag_idx, pt_idx);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        Get_partner();
                    }
                });
                dialog.show();
            }
        });

    }

    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_partner_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        companyItems = new Gson().fromJson(result_item, new TypeToken<ArrayItem<CompanyData>>() {
                        }.getType());

                        if (companyItems.isSuccess()) {
                            Set_Content();

                        } else {
                            Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                        }

                    } else if (url.equals("proc_admin_company_delete")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        Common.getInstance().toastShow(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString());
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Get_partner();
                        }
                    }

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

                cp_managePB.setVisibility(View.GONE);
            }
        };
    }
}
