package kr.co.compcareworker.Fragment.Enterprise.Deal_Est_List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
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.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.DealList.DealListData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.DealListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

import static android.content.Context.INPUT_METHOD_SERVICE;

@SuppressLint("ValidFragment")
public class DealList_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;

    ArrayItem<DealListData> items;

    /**
     * 상단 컨텐츠
     */
    //TextView tv_act_deal_list_name, tv_act_deal_list_office, tv_act_deal_list_line;
    //LinearLayout ll_act_deal_list_content;
    TextView sort;
    ImageView find;
    EditText findText;
    String sortType = "ok_dt";

    /**
     * 거래명세서 목록
     */
    RecyclerView list;
    TextView noneList;
    DealListRecyclerAdapter adapter;
    boolean dealList = false;

    /**
     * 프로그래스바
     */
    ProgressBar progress;

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

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

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

    public DealList_Fragment() {
    }

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

        /** 상단 컨텐츠*/
        /*tv_act_deal_list_name = v.findViewById(R.id.tv_act_deal_list_name);
        tv_act_deal_list_office = v.findViewById(R.id.tv_act_deal_list_office);
        tv_act_deal_list_line = v.findViewById(R.id.tv_act_deal_list_line);
        ll_act_deal_list_content = v.findViewById(R.id.ll_act_deal_list_content);*/

        sort = v.findViewById(R.id.sort);
        find = v.findViewById(R.id.find);
        findText = v.findViewById(R.id.findText);
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(findText.getWindowToken(), 0);

        /** 거래명세서 목록*/
        list = v.findViewById(R.id.list);
        noneList = v.findViewById(R.id.noneList);
        adapter = new DealListRecyclerAdapter(getContext(), hdr);
        list.setAdapter(adapter);

        /** 프로그래스바*/
        progress = v.findViewById(R.id.progress);

        init_Handler();
        init_Listener();

        Get_Contents();

        return v;
    }

    void Get_Contents() {
        progress.setVisibility(View.VISIBLE);
        HashMap<String, String> dt = new HashMap<>();
        dt.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        dt.put("cp_idx", fa.enterpriseItem.getArrayitem().getCpIdx());
        dt.put("sfield", sortType);
        dt.put("skeyword", findText.getText().toString());
        new ApiClient(dt, "proc_invoice_list", hdr);
    }

    void Set_Contents() {
        /** 상단 컨텐츠*/
        /*tv_act_deal_list_name.setText(fa.enterpriseItem.getArrayitem().getPtName());
        tv_act_deal_list_office.setText(fa.enterpriseItem.getArrayitem().getCpName());
        tv_act_deal_list_line.setText(fa.enterpriseItem.getArrayitem().getAlMachineData().get(fa.machinePosition).getMcAirline());
        if (fa.enterpriseItem.getArrayitem().getAlMachineData().get(fa.machinePosition).getItems().size() != 0){
            ll_act_deal_list_content.removeAllViews();
            for (int i = 0; i < fa.enterpriseItem.getArrayitem().getAlMachineData().get(fa.machinePosition).getItems().size(); i++) {
                LinearLayout.LayoutParams LayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                LinearLayout.LayoutParams mainLayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                LinearLayout.LayoutParams timeLayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                LayoutParam.setMargins(0, 40, 0, 0);
                mainLayoutParam.setMargins(0, 10, 0, 0);
                timeLayoutParam.setMargins(0, 10, 0, 0);

                LinearLayout layout = new LinearLayout(getContext());
                TextView mainTv = new TextView(getContext());
                TextView timeTv = new TextView(getContext());

                layout.setOrientation(LinearLayout.VERTICAL);
                layout.setLayoutParams(LayoutParam);

                mainTv.setText(String.format("%s (%s)",
                        fa.enterpriseItem.getArrayitem().getAlMachineData().get(fa.machinePosition).getItems().get(i).getProductData().getPdName(),
                        fa.enterpriseItem.getArrayitem().getAlMachineData().get(fa.machinePosition).getItems().get(i).getDelFlagStr()));
                mainTv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16f);
                mainTv.setLayoutParams(mainLayoutParam);
                mainTv.setTypeface(null, Typeface.BOLD);

                timeTv.setText(String.format("- 예상 소모품 정비 %sh", fa.enterpriseItem.getArrayitem().getAlMachineData().get(fa.machinePosition).getItems().get(i).getMcLastHour()));
                timeTv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16f);
                timeTv.setLayoutParams(timeLayoutParam);
                timeTv.setTypeface(null, Typeface.BOLD);

                layout.addView(mainTv);
                layout.addView(timeTv);
                ll_act_deal_list_content.addView(layout);
            }
        }*/

        /** 거래명세서 리스트*/
        if (dealList) {
            adapter.addItem(items.getArrayitem());
        }

        progress.setVisibility(View.GONE);
    }

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

                        if (items.isSuccess()) {
                            dealList = true;
                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_LONG).show();
                            list.setVisibility(View.GONE);
                            noneList.setVisibility(View.VISIBLE);
                        }

                        Set_Contents();
                    }
                }
            }
        };
    }

    private void init_Listener() {
        sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] arr_str = new String[]{"거래일", "AIRLINE"};
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                alertDialogBuilder.setSingleChoiceItems(arr_str, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        sort.setText(arr_str[which] + " ▼");
                        if (which == 0) {
                            sortType = "ok_dt";
                            findText.setText("");
                            //findText.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
                            findText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
                            findText.setHint("ex)2019-01-01");
                        } else {
                            sortType = "cp_airline";
                            findText.setText("");
                            //findText.setInputType(InputType.TYPE_CLASS_TEXT);
                            findText.setInputType(InputType.TYPE_CLASS_TEXT);
                            findText.setHint("AIRLINE 을 입력하세요.");
                        }
                        dialog.dismiss();
                    }
                });
                alertDialogBuilder.show();
            }
        });

        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Get_Contents();
            }
        });
    }
}
