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

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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
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.viewpager.widget.ViewPager;

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.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.WebviewAct;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ImageList.ImageListData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ImageAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;

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

    FragmentActivity fa;

    ProgressBar progress;

    /**
     * 이미지
     */
    ViewPager pager;
    ImageAdapter imgAdapter;
    TextView noneImg;

    /**
     * 접수내용
     */
    TextView contents, name, tel, dt, status;

    /**
     * 답변
     */
    EditText comment;

    /**
     * 버튼
     */
    TextView workAdd, save, close;

    String cp_idx, ck_idx;
    String ck_status;

    ArrayItem<ImageListData> items;

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

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

    @SuppressLint("ValidFragment")
    public ImageCheckDetail_Fragment(Handler handler, String cp_idx, String ck_idx) {
        this.handler = handler;
        this.cp_idx = cp_idx;
        this.ck_idx = ck_idx;
    }

    public ImageCheckDetail_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_image_check_detail, container, false);
        progress = v.findViewById(R.id.progress);
        pager = v.findViewById(R.id.pager);
        noneImg = v.findViewById(R.id.noneImg);
        contents = v.findViewById(R.id.contents);
        name = v.findViewById(R.id.name);
        tel = v.findViewById(R.id.tel);
        dt = v.findViewById(R.id.dt);
        status = v.findViewById(R.id.status);
        comment = v.findViewById(R.id.comment);
        workAdd = v.findViewById(R.id.workAdd);
        save = v.findViewById(R.id.save);
        close = v.findViewById(R.id.close);

        init_Handler();
        init_Listener();

        Get_Contents();

        return v;
    }

    void Get_Contents() {
        progress.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        data.put("ck_idx", ck_idx);
        new ApiClient(data, "proc_checkup_list", hdr);
    }

    void Set_Contents() {
        ImageListData item = items.getArrayitem().get(0);

        ArrayList<String> imageUriArray = new ArrayList<>();
        for (int i = 0; i < item.getFileData().size(); i++) {
            imageUriArray.add(item.getFileData().get(i).getUrl());
        }

        if (imageUriArray.size() != 0) {
            noneImg.setVisibility(View.GONE);
            pager.setVisibility(View.VISIBLE);

            imgAdapter = new ImageAdapter(getContext(), imageUriArray);
            pager.setAdapter(imgAdapter);
        } else {
            noneImg.setVisibility(View.VISIBLE);
            pager.setVisibility(View.GONE);
        }

        contents.setText(item.getCkCont());
        name.setText(item.getMbName());
        tel.setText(item.getMbPhone());
        try {
            SimpleDateFormat beforeSDF = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date beforeDate = beforeSDF.parse(item.getInsDt());
            SimpleDateFormat afterSDF = new SimpleDateFormat("yyyy.MM.dd");
            String afterDate = afterSDF.format(beforeDate);
            dt.setText(afterDate);
        } catch (Exception e) {
            dt.setText(item.getInsDt().split(" ")[0]);
        }

        status.setText(item.getCkStatusStr());

        if (item.getCkStatusStr().equals("대기")) {
            comment.setText("");
            comment.setEnabled(true);
        } else {
            comment.setText(item.getCkAnswer());
            comment.setEnabled(false);
        }

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

                        if (items.isSuccess()) {
                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), items.getMessage(), Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        }
                    } else if (url.equals("proc_checkup_update")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), "처리되었습니다.", Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        };
    }

    private void init_Listener() {
        workAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String incodeUrl = URLEncoder.encode("https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/work/write?pt_idx=" + fa.enterpriseItem.getArrayitem().getPtIdx() + "&cp_idx=" + fa.enterpriseItem.getArrayitem().getCpIdx());
                Intent intent = new Intent(getContext(), WebviewAct.class);
                intent.putExtra("title", "서비스 등록");
                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/" + fa.userItem.getArrayitem().getMbId() + "/?url=" + incodeUrl);
                startActivity(intent);
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (comment.isEnabled() == false) {
                    Toast.makeText(getContext(), "이미 완료되었습니다.", Toast.LENGTH_LONG).show();
                    return;
                }

                String[] arr_str = new String[]{"정상", "점검필요"};
                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) {
                        if (which == 0) ck_status = "OK";
                        else ck_status = "WORK";

                        HashMap<String, String> data = new HashMap<>();
                        data.put("ck_idx", ck_idx);
                        data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                        data.put("ck_status", ck_status);
                        data.put("ck_answer", comment.getText().toString());
                        new ApiClient(data, "proc_checkup_update", hdr);
                        dialog.dismiss();
                    }
                });
                alertDialogBuilder.show();


            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }
}
