package kr.co.compcarecompany.Util.CustomView;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import gun0912.tedimagepicker.builder.TedImagePicker;
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.AlarmData;
import kr.co.compcarecompany.Data.Product.AlarmReportData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ReportAdapter;
import kr.co.compcarecompany.Util.Adapter.ReportImageAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

public class ReportDialog extends Dialog {

    Context context;
    private TextView dlg_timeTV, dlg_sensorTV, dlg_valueTV, dlg_sensor_informTV, dlg_product_nameTV, dlg_macTV, dlg_saveTV, dlg_closeTV, dlg_work_dateTV;
    private RecyclerView dlg_reportRV, dlg_photoRV;
    private LinearLayout dlg_photo_addLL;
    private EditText dlg_workerET, dlg_contentET;
    private String mcl_idx, ag_idx, pt_idx, mem_id, mc_airline, cp_idx;
    private Handler hdr;
    private ReportImageAdapter photo_adapter;
    private ReportAdapter report_adapter;
    private FragmentActivity frag;
    private DatePickerDialog.OnDateSetListener callbackMethod;
    private RadioButton reportRB1, reportRB2, reportRB3, reportRB4;
    private RadioGroup reportRG;

    private ArrayList<String> arr = new ArrayList<>();
    private ArrayItem_<AlarmReportData> alarm_report;
    private ArrayItem<FileDatum> alarm_photo;
    private ArrayItem<AlarmData> alarmArray;
    private ArrayList<String> mc_idx_list;
    private boolean is_product_alarm = false;
    private ArrayList<AlarmData> alarm_data = new ArrayList<>();

    public ReportDialog(@NonNull Context context, Handler hdr, String ag_idx, String pt_idx, String mem_id, String mc_airline, String cp_idx, FragmentActivity frag) {
        super(context);
        this.context = context;
        this.hdr = hdr;
        this.ag_idx = ag_idx;
        this.pt_idx = pt_idx;
        this.mem_id = mem_id;
        this.mc_airline = mc_airline;
        this.cp_idx = cp_idx;
        this.frag = frag;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.dlg_alarm_report_new);

        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.90f);

        thisWindow.setLayout(x, y);

        dlg_workerET = findViewById(R.id.dlg_workerET);
        dlg_work_dateTV = findViewById(R.id.dlg_work_dateTV);
        dlg_contentET = findViewById(R.id.dlg_contentET);
        dlg_photo_addLL = findViewById(R.id.dlg_photo_addLL);
        dlg_photoRV = findViewById(R.id.dlg_photoRV);
        dlg_saveTV = findViewById(R.id.dlg_saveTV);
        dlg_closeTV = findViewById(R.id.dlg_closeTV);
        dlg_reportRV = findViewById(R.id.dlg_reportRV);
        reportRG = findViewById(R.id.reportRG);
        reportRB1 = findViewById(R.id.reportRB1);
        reportRB2 = findViewById(R.id.reportRB2);
        reportRB3 = findViewById(R.id.reportRB3);
        reportRB4 = findViewById(R.id.reportRB4);

        dlg_workerET.requestFocus();
        dlg_workerET.setText(frag.userItem.getArrayitem().getMbName());

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

        dlg_photoRV.setLayoutManager(new GridLayoutManager(getContext(), 4));
        photo_adapter = new ReportImageAdapter(getContext(), itemHeight);
        dlg_photoRV.setAdapter(photo_adapter);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        dlg_reportRV.setLayoutManager(layoutManager);
        report_adapter = new ReportAdapter(getContext());
        dlg_reportRV.setAdapter(report_adapter);

        mc_idx_list = new ArrayList<>();

        if(alarmArray != null){
            alarm_data.clear();

            for (int i = 0; i < alarmArray.getArrayitem().size(); i++) {
                if (alarmArray.getArrayitem().get(i).isChecked()) {
                    alarm_data.add(alarmArray.getArrayitem().get(i));
                    mc_idx_list.add(alarmArray.getArrayitem().get(i).getMachineData().getMcIdx());
                    if (alarmArray.getArrayitem().get(i).getSensor().equals("200")){
                        is_product_alarm = true;
                    }
                }
            }
        }

        Date currentTime = Calendar.getInstance().getTime();
        String today = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault()).format(currentTime);
        dlg_work_dateTV.setText(today);

        init_Handler();
        init_Listener();
    }

    void init_Listener() {

        //사진추가 버튼 클릭리스너
        dlg_photo_addLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectSize = photo_adapter.getItemCount();
                if (selectSize < 4) {
                    TedImagePicker.with(context)
                            .startMultiImage(uriList -> {
                                for (int i = 0; i < uriList.size(); i++) {
                                    arr.add(uriList.get(i).toString());
                                }
                                photo_adapter.addItem(arr);
                            });
//                    TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(getContext()).setImageProvider(new TedBottomPicker.ImageProvider() {
//                        @Override
//                        public void onProvideImage(ImageView imageView, Uri imageUri) {
//                            Glide.with(getContext()).load(imageUri).apply(RequestOptions.centerCropTransform()).into(imageView);
//                        }
//                    }).setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
//                        @Override
//                        public void onImagesSelected(ArrayList<Uri> uriList) {
//
//                            for (int i = 0; i < uriList.size(); i++) {
//                                arr.add(uriList.get(i).toString());
//                            }
//                            photo_adapter.addItem(arr);
//                        }
//                    })
//                            .setCompleteButtonText("저장")
//                            .setPeekHeight(2400)
//                            .setPreviewMaxCount(1000).setSelectMaxCount(4 - selectSize).create();
//                    tedBottomPicker.show(frag.getSupportFragmentManager());

                } else {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("사진은 최대 4장까지 등록가능합니다.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                }
            }
        });

        //사진삭제버튼 클릭리스너
        photo_adapter.setOnItemClickListener(new ReportImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                photo_adapter.removeItem(position);
                arr.remove(position);
            }
        });

        //닫기버튼 클릭리스너
        dlg_closeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        //저장버튼 클릭리스너
        dlg_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = dlg_workerET.getText().toString();
                String work_day = dlg_work_dateTV.getText().toString();
                String content = dlg_contentET.getText().toString();

                String content_quick = "";
                if(reportRB1.isChecked()){
                    content_quick = "(점검완료)";
                }

                if(reportRB2.isChecked()){
                    content_quick = "(사후조치)";
                }

                if(reportRB3.isChecked()){
                    content_quick = "(A/S 요청)";
                }

                if(reportRB4.isChecked()){
                    content_quick = "(기타)";
                }

                if (TextUtils.isEmpty(name)) {
                    Common.getInstance().toastShow(getContext(), "작업자 이름을 입력해주세요.");
                    return;
                }

                if (TextUtils.isEmpty(content) && TextUtils.isEmpty(content_quick)) {
                    Common.getInstance().toastShow(getContext(), "작업 내용을 입력하거나 선택하세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ar_worker", name);
                data.put("ar_content", content);
                data.put("ar_content_quick", content_quick);
                data.put("ag_idx", ag_idx);
                data.put("pt_idx", pt_idx);
                data.put("ar_work_date", work_day);
                data.put("mc_airline", mc_airline);
                data.put("cp_idx", cp_idx);
                data.put("mem_id", mem_id);

                Log.d("데이터확인@@@@", data.toString());

                ArrayList<Uri> photo_uri = new ArrayList<>();
                for (int i = 0; i < arr.size(); i++) {
                    photo_uri.add(Uri.parse(arr.get(i)));
                }

                new ApiClient(data, "proc_alarm_report_write2", photo_uri, hdr);
            }
        });

        dlg_work_dateTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getContext(), callbackMethod, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
                dialog.getDatePicker().setMaxDate(Calendar.getInstance().getTimeInMillis());
                dialog.show();
            }
        });

        callbackMethod = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                int month = monthOfYear + 1;
                String con_month = month+"";
                if(month < 10){
                    con_month = "0"+con_month;
                }

                String con_day = dayOfMonth + "";
                if (dayOfMonth < 10) {
                    con_day = "0" + con_day;
                }
                dlg_work_dateTV.setText(year + "." + con_month + "." + con_day);
            }
        };
    }

    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_alarm_report_write2")) {
                        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(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            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();
                }
            }
        };
    }
}
