package kr.co.compcarecompany.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
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.ArrayList;
import java.util.HashMap;
import java.util.List;

import kr.co.compcarecompany.Activity.FragmentActivity;
import kr.co.compcarecompany.Data.ArrayItem;
import kr.co.compcarecompany.Data.ArrayItem_;
import kr.co.compcarecompany.Data.FileDatum;
import kr.co.compcarecompany.Data.Product.AlarmReportData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class AlarmReportDialog extends Dialog {

    private TextView item_report_nameTV, item_report_dateTV, item_report_contentTV, item_report_completeTV, item_report_modifyTV;
    private RecyclerView item_report_photoRV;
    private String mcl_idx, pt_idx, mem_id;
    private Handler hdr;
    private ServiceImageGridAdapter photo_adapter;
    private ProgressBar dlg_alarm_reportPB;

    private ArrayItem_<AlarmReportData> alarm_report;
    private ArrayItem<FileDatum> alarm_photo;

    //작업일지 클릭 리스너
    private AlarmReportDialog.completeListener completeListener;

    public interface completeListener {
        void clickBtn(Bundle bundle);
    }

    public AlarmReportDialog(@NonNull Context context, Handler hdr, String mcl_idx, String pt_idx, String mem_id, AlarmReportDialog.completeListener completeListener) {
        super(context);
        this.hdr = hdr;
        this.mcl_idx = mcl_idx;
        this.pt_idx = pt_idx;
        this.mem_id = mem_id;
        this.completeListener = completeListener;
    }

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

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);

        Window thisWindow = this.getWindow();

        int x = (int) (size.x * 0.95f);
        int y = (int) (size.y * 0.80f);

        thisWindow.setLayout(x, y);
        item_report_nameTV = findViewById(R.id.item_report_nameTV);
        item_report_dateTV = findViewById(R.id.item_report_dateTV);
        item_report_contentTV = findViewById(R.id.item_report_contentTV);
        item_report_completeTV = findViewById(R.id.item_report_completeTV);
        item_report_modifyTV = findViewById(R.id.item_report_modifyTV);
        item_report_photoRV = findViewById(R.id.item_report_photoRV);
        dlg_alarm_reportPB = findViewById(R.id.dlg_alarm_reportPB);

        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, getContext().getResources().getDisplayMetrics());
        int itemHeight = x - (item_report_photoRV.getPaddingLeft() + item_report_photoRV.getPaddingRight() - px * 4) / 5;

        item_report_photoRV.setLayoutManager(new GridLayoutManager(getContext(), 5));
        photo_adapter = new ServiceImageGridAdapter(getContext(), itemHeight);
        item_report_photoRV.setAdapter(photo_adapter);

        init_Handler();
        init_Listener();
        Get_ReportData();
        dlg_alarm_reportPB.setVisibility(View.VISIBLE);
    }

    void Get_ReportData() {
        HashMap<String, String> data = new HashMap<>();
        data.put("mcl_idx", mcl_idx);
        new ApiClient(data, "proc_get_alarm_report", hdr);
    }

    void Get_photo() {
        HashMap<String, String> data = new HashMap<>();
        data.put("pt_idx", pt_idx);
        data.put("ar_idx", alarm_report.getArrayitem().getArIdx());
        new ApiClient(data, "proc_get_alarm_image", hdr);
    }

    void Set_Contents() {

        item_report_nameTV.setText(alarm_report.getArrayitem().getArWorker());
        item_report_dateTV.setText(alarm_report.getArrayitem().getArInsDt());
        item_report_contentTV.setText(alarm_report.getArrayitem().getArContent());
    }

    void init_Listener() {

        //수정버튼 클릭리스너
        item_report_modifyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //작업일지 프래그먼트로 이동

                if(alarm_report.getArrayitem().getArAuthorizer() != null){
                    Common.getInstance().toastShow(getContext(), "완료처리 된 일지는 수정할 수 없습니다.");
                    return;
                }

                List<String> report_list = new ArrayList<>();
                report_list.add(alarm_report.getArrayitem().getArIdx());

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "작업일지");
                intent.putExtra("type", "alarm_report");
                intent.putStringArrayListExtra("value1", (ArrayList<String>) report_list);
                intent.putExtra("value2", "modify");
                getContext().startActivity(intent);
                dismiss();
            }
        });

        //완료버튼 클릭리스너
        item_report_completeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(alarm_report.getArrayitem().getArAuthorizer() != null){
                    Common.getInstance().toastShow(getContext(), "이미 완료 처리 된 일지입니다.");
                    return;
                }

                //작업일지 완료처리
                HashMap<String, String> data = new HashMap<>();
                data.put("ar_idx", alarm_report.getArrayitem().getArIdx());
                data.put("mcl_idx", mcl_idx);
                data.put("mem_id", mem_id);
                Log.d("데이터@@@@", data.toString());
                new ApiClient(data, "proc_alarm_report_complete", hdr);
            }
        });
    }

    void init_Handler() {

        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String url = msg.getData().getString("url");

                if (msg.what == 1) {

                    if (url.equals("proc_get_alarm_report")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        alarm_report = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<AlarmReportData>>() {
                        }.getType());

                        if(alarm_report.isSuccess()){
                            Get_photo();

                        }else {
                            Common.getInstance().toastShow(getContext(), "작업일지 가져오기를 실패했습니다.");
                        }

                    } else if (url.equals("proc_get_alarm_image")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        alarm_photo = new Gson().fromJson(result_item, new TypeToken<ArrayItem<FileDatum>>() {
                        }.getType());

                        if(result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")){
                            photo_adapter.addItem(alarm_photo.getArrayitem());
                        }

                        Set_Contents();

                    } else if (url.equals("proc_alarm_report_complete")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if(result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")){
                            Bundle bundle = new Bundle();
                            bundle.putString("complete", "Y");
                            completeListener.clickBtn(bundle);
                            dismiss();

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

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

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