package kr.co.compcarecompany.Fragment.Menu;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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.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.Company.CompanyData;
import kr.co.compcarecompany.Data.Company.EngineerData;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.Adapter.ServiceImageAdapter;
import kr.co.compcarecompany.Util.Api.ApiClient;
import kr.co.compcarecompany.Util.Common;

@SuppressLint("ValidFragment")
public class Service_registration_Fragment extends Fragment {

    Handler handler, hdr;
    FragmentActivity fa;
    EditText service_nameEV, service_telEV, service_memoET;
    TextView service_dateTV, service_date_pickerTV, cp_nameTV, service_pt_nameTV;
    HorizontalScrollView service_timeHSV;
    RadioGroup serviceRG;
    RadioButton serviceRB_01, serviceRB_02, serviceRB_03, serviceRB_04, serviceRB_05, serviceRB_06, serviceRB_07, serviceRB_08,
            serviceRB_09, serviceRB_10, serviceRB_11, serviceRB_12, serviceRB_13, serviceRB_14, serviceRB_15, serviceRB_16,
            serviceRB_17, serviceRB_18, serviceRB_19, serviceRB_20, serviceRB_21, serviceRB_22, serviceRB_23, serviceRB_24;
    LinearLayout service_add_pictureLL;
    RecyclerView service_pictureRV;
    CheckBox check_01, check_02, check_03, check_04, check_05, check_06,
            check_07, check_08, check_09, check_10, check_11, check_12;
    RelativeLayout service_registerRL;
    CompanyData companyData;
    ArrayList<String> arr = new ArrayList<>();
    public ArrayList<Uri> imageUriArray;
    ServiceImageAdapter service_img_adapter;
    private DatePickerDialog.OnDateSetListener callbackMethod;
    /**
     * 방문기사
     */
    RadioGroup engineerRG;
    LinearLayout engineerLL;
    HorizontalScrollView scrollView;
    ArrayItem<EngineerData> engineer_array;
    EngineerData engineer_data;
    String[] engineer_id;
    String select_engineer_id;
    String engineer_name;
    String wr_worker_name, wr_worker_id;

    @SuppressLint("ValidFragment")
    public Service_registration_Fragment(Handler handler, CompanyData companyData) {

        this.handler = handler;
        this.companyData = companyData;
    }

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

        service_nameEV = v.findViewById(R.id.service_nameEV);
        service_telEV = v.findViewById(R.id.service_telEV);
        service_memoET = v.findViewById(R.id.service_memoET);
        service_dateTV = v.findViewById(R.id.service_dateTV);
        service_date_pickerTV = v.findViewById(R.id.service_date_pickerTV);
        service_timeHSV = v.findViewById(R.id.service_timeHSV);
        cp_nameTV = v.findViewById(R.id.cp_nameTV);
        service_pt_nameTV = v.findViewById(R.id.service_pt_nameTV);

        serviceRG = v.findViewById(R.id.serviceRG);
        serviceRB_01 = v.findViewById(R.id.serviceRB_01);
        serviceRB_02 = v.findViewById(R.id.serviceRB_02);
        serviceRB_03 = v.findViewById(R.id.serviceRB_03);
        serviceRB_04 = v.findViewById(R.id.serviceRB_04);
        serviceRB_05 = v.findViewById(R.id.serviceRB_05);
        serviceRB_06 = v.findViewById(R.id.serviceRB_06);
        serviceRB_07 = v.findViewById(R.id.serviceRB_07);
        serviceRB_08 = v.findViewById(R.id.serviceRB_08);
        serviceRB_09 = v.findViewById(R.id.serviceRB_09);
        serviceRB_10 = v.findViewById(R.id.serviceRB_10);
        serviceRB_11 = v.findViewById(R.id.serviceRB_11);
        serviceRB_12 = v.findViewById(R.id.serviceRB_12);
        serviceRB_13 = v.findViewById(R.id.serviceRB_13);
        serviceRB_14 = v.findViewById(R.id.serviceRB_14);
        serviceRB_15 = v.findViewById(R.id.serviceRB_15);
        serviceRB_16 = v.findViewById(R.id.serviceRB_16);
        serviceRB_17 = v.findViewById(R.id.serviceRB_17);
        serviceRB_18 = v.findViewById(R.id.serviceRB_18);
        serviceRB_19 = v.findViewById(R.id.serviceRB_19);
        serviceRB_20 = v.findViewById(R.id.serviceRB_20);
        serviceRB_21 = v.findViewById(R.id.serviceRB_21);
        serviceRB_22 = v.findViewById(R.id.serviceRB_22);
        serviceRB_23 = v.findViewById(R.id.serviceRB_23);
        serviceRB_24 = v.findViewById(R.id.serviceRB_24);

        service_add_pictureLL = v.findViewById(R.id.service_add_pictureLL);
        service_pictureRV = v.findViewById(R.id.service_pictureRV);

        check_01 = v.findViewById(R.id.check_01);
        check_02 = v.findViewById(R.id.check_02);
        check_03 = v.findViewById(R.id.check_03);
        check_04 = v.findViewById(R.id.check_04);
        check_05 = v.findViewById(R.id.check_05);
        check_06 = v.findViewById(R.id.check_06);
        check_07 = v.findViewById(R.id.check_07);
        check_08 = v.findViewById(R.id.check_08);
        check_09 = v.findViewById(R.id.check_09);
        check_10 = v.findViewById(R.id.check_10);
        check_11 = v.findViewById(R.id.check_11);
        check_12 = v.findViewById(R.id.check_12);

        service_registerRL = v.findViewById(R.id.service_registerRL);
        int itemHeight = (Common.getInstance().getWidth(getActivity())) / 2;
        service_img_adapter = new ServiceImageAdapter(getActivity(), itemHeight);
        service_pictureRV.setAdapter(service_img_adapter);
        imageUriArray = new ArrayList<>();

        /**방문기사*/
        engineerLL = v.findViewById(R.id.engineerLL);
        engineerRG = new RadioGroup(getContext());
        engineerRG.setOrientation(LinearLayout.HORIZONTAL);
        scrollView = new HorizontalScrollView(getContext());
        scrollView.setHorizontalScrollBarEnabled(false);
        engineerLL.addView(scrollView);
        scrollView.addView(engineerRG);

        init_Handler();
        init_Listener();
        Get_Engineer();

        return v;
    }

    public void Get_Engineer() {
        HashMap<String, String> data = new HashMap<>();
        data.put("mb_type", "ENGINEER");
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        new ApiClient(data, "proc_engineer_view", hdr);
    }


    void Set_Contents() {

        service_pt_nameTV.setText(companyData.getPtName());
        cp_nameTV.setText(companyData.getCpName());
        service_nameEV.setText(fa.userItem.getArrayitem().getMbName());
        service_telEV.setText(fa.userItem.getArrayitem().getMbPhone());

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

        /**방문시간 현재시간 기준으로 포커스*/
        String time = new SimpleDateFormat("HH", Locale.getDefault()).format(currentTime);
        int set_time = Integer.parseInt(time) + 1;
        if (set_time == 24) {
            set_time = 0;
        }

        RadioButton[] timeRbtn = {serviceRB_01, serviceRB_02, serviceRB_03, serviceRB_04, serviceRB_05, serviceRB_06, serviceRB_07, serviceRB_08,
                serviceRB_09, serviceRB_10, serviceRB_11, serviceRB_12, serviceRB_13, serviceRB_14, serviceRB_15, serviceRB_16, serviceRB_17,
                serviceRB_18, serviceRB_19, serviceRB_20, serviceRB_21, serviceRB_22, serviceRB_23};

        timeRbtn[set_time].setChecked(true);

        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
        int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics());

        int finalSet_time = set_time;
        service_timeHSV.postDelayed(new Runnable() {
            @Override
            public void run() {
                service_timeHSV.scrollTo((finalSet_time * width) + (margin * (finalSet_time)), 0);
            }
        }, 100);

        /**서비스 접수*/
        service_registerRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //상세증상
                String detail = "";
                CheckBox[] checked = {check_01, check_02, check_03, check_04, check_05, check_06, check_07, check_08, check_09, check_10, check_11, check_12};
                for (int i = 0; i < checked.length; i++) {
                    if (checked[i].isChecked()) {
                        detail = detail + "(" + checked[i].getText().toString() + ")";
                    }
                }

                if (TextUtils.isEmpty(detail) || detail.equals("")) {
                    Toast.makeText(getContext(), "상세증상을 선택하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                //방문시간
                String visit_time = "";
                RadioButton[] visitTimeRbtn = {serviceRB_01, serviceRB_02, serviceRB_03, serviceRB_04, serviceRB_05, serviceRB_06, serviceRB_07, serviceRB_08,
                        serviceRB_09, serviceRB_10, serviceRB_11, serviceRB_12, serviceRB_13, serviceRB_14, serviceRB_15, serviceRB_16, serviceRB_17,
                        serviceRB_18, serviceRB_19, serviceRB_20, serviceRB_21, serviceRB_22, serviceRB_23};

                String time = new SimpleDateFormat("HH", Locale.getDefault()).format(currentTime);
                int set_time = Integer.parseInt(time) + 1;
                if (set_time == 24) {
                    set_time = 0;
                }

                visitTimeRbtn[set_time].setChecked(true);

                for (int i = 0; i < visitTimeRbtn.length; i++) {
                    if (visitTimeRbtn[i].isChecked()) {
                        visit_time = visitTimeRbtn[i].getText().toString();
                    }
                }

                visit_time = visit_time + ":00";
                String visit_date = "";
                visit_date = service_dateTV.getText().toString();

                visit_time = visit_time.replace("오전 ", "");
                visit_time = visit_time.replace("오후 ", "");
                visit_date = visit_date.replace("년 ", "-");
                visit_date = visit_date.replace("월 ", "-");
                visit_date = visit_date.replace("일", " ");

                String call_date = visit_date + visit_time;

                String memo = service_memoET.getText().toString();

                //접수내용
                if (TextUtils.isEmpty(memo)) {
                    Common.getInstance().toastShow(getContext(), "접수 내용을 입력하세요.");
                    return;
                }

                if (TextUtils.isEmpty(wr_worker_name)) {
                    Common.getInstance().toastShow(getContext(), "방문을 원하는 기사를 선택하세요.");
                    return;
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", companyData.getAgIdx());
                data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                data.put("pt_idx", companyData.getPtIdx());
                data.put("cp_idx", companyData.getCpIdx());
                if (companyData.getCpAirline() != null) {
                    data.put("cp_airline", companyData.getCpAirline() + "");
                } else {
                    data.put("cp_airline", "기본값");
                }
                data.put("wr_startdt", call_date);
                data.put("wo_memo", detail);
                data.put("wo_man", service_nameEV.getText().toString());
                data.put("wo_tel", service_telEV.getText().toString());
                data.put("wr_worker_name", wr_worker_name);
                data.put("wr_worker_id", wr_worker_id);
                data.put("wo_memo_orders", memo);

                ArrayList<Uri> uriData = new ArrayList<>();

                for (int i = 0; i < arr.size(); i++) {
                    uriData.add(Uri.parse(arr.get(i)));
                }

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

                new ApiClient(data, "proc_admin_service_registration", uriData, hdr);

            }
        });


        /** 사진 촬영 */
        service_add_pictureLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int selectSize = service_img_adapter.getItemCount();
                if (selectSize < 15) {
                    TedImagePicker.with(requireContext())
                            .startMultiImage(uriList -> {
                                imageUriArray.clear();
                                imageUriArray.addAll(uriList);

                                for (int i = 0; i < uriList.size(); i++) {
                                    arr.add(uriList.get(i).toString());
                                }

                                service_img_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) {
//
//                            imageUriArray.clear();
//                            imageUriArray.addAll(uriList);
//
//                            for (int i = 0; i < uriList.size(); i++) {
//                                arr.add(uriList.get(i).toString());
//                            }
//
//                            service_img_adapter.addItem(arr);
//
//                        }
//                    })
//                            .setCompleteButtonText("저장")
//                            .setPeekHeight(2400)
//                            .setPreviewMaxCount(1000).setSelectMaxCount(15 - selectSize).create();
//                    tedBottomPicker.show(getActivity().getSupportFragmentManager());
                } else {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("사진은 최대 15개까지 등록가능합니다.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                }
            }
        });

        /**추가된 사진 삭제버튼 클릭*/
        service_img_adapter.setOnItemClickListener(new ServiceImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

                service_img_adapter.removeItem(position);
                arr.remove(position);
            }
        });
    }

    private void init_Listener() {

        service_date_pickerTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog dialog = new DatePickerDialog(getContext(), callbackMethod, Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
                dialog.getDatePicker().setMinDate(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;
                service_dateTV.setText(year + "년 " + month + "월 " + dayOfMonth + "일");

                Log.e("DatePicker ===", year + "년" + month + "월" + dayOfMonth + "일");
            }
        };

        //연락처 입력시 자동으로 하이픈 추가
        service_telEV.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        engineerRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton button = group.findViewById(checkedId);
                wr_worker_name = button.getText().toString();
                wr_worker_id = engineer_id[checkedId];
            }
        });
    }


    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_engineer_view")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        engineer_array = new Gson().fromJson(result_item, new TypeToken<ArrayItem<EngineerData>>() {
                        }.getType());

                        if (engineer_array.isSuccess()) {

                            if (engineer_array.size() > 0) {

                                engineer_id = new String[engineer_array.getArrayitem().size()];

                                for (int i = 0; i < engineer_array.getArrayitem().size(); ++i) {

                                    engineer_data = engineer_array.getArrayitem().get(i);
                                    engineer_id[i] = engineer_data.getEngineerId();
                                    RadioButton radioButton = new RadioButton(getContext());
                                    radioButton.setId(i);
                                    radioButton.setGravity(Gravity.CENTER);
                                    radioButton.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.radio_selector));
                                    radioButton.setText(engineer_data.getMbName());
                                    radioButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                                    radioButton.setButtonDrawable(null);

                                    //버튼크기 및 마진설정
                                    int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
                                    int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
                                    int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics());

                                    RadioGroup.LayoutParams childParam1 = new RadioGroup.LayoutParams(width, height);
                                    childParam1.setMargins(0, 0, right, 0);
                                    radioButton.setLayoutParams(childParam1);

                                    //버튼 체크되었을 때 색상변화
                                    int[][] states = new int[][]{
                                            new int[]{-android.R.attr.state_checked}, // unchecked
                                            new int[]{android.R.attr.state_pressed}  // checked
                                    };
                                    int[] colors = new int[]{
                                            Color.GRAY,
                                            Color.YELLOW
                                    };
                                    ColorStateList myList = new ColorStateList(states, colors);
                                    radioButton.setButtonTintList(myList);

                                    String name = engineer_data.getMbName();
                                    if (name.equals(fa.userItem.getArrayitem().getMbName())) {
                                        radioButton.setChecked(true);
                                        select_engineer_id = engineer_id[i];
                                        engineer_name = name;
                                    }

                                    radioButton.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            engineer_name = radioButton.getText().toString();
                                            select_engineer_id = engineer_id[radioButton.getId()];
                                        }
                                    });

                                    engineerRG.addView(radioButton, childParam1);
                                }
                            }

                            Set_Contents();

                        } else {

                            Toast.makeText(getContext(), engineer_array.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    } else if (url.equals("proc_admin_service_registration")) {
                        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();
                            getActivity().finish();

                        } 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();
                }
            }
        };
    }
}
