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

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
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 com.ortiz.touchview.TouchImageView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;

import java.util.ArrayList;
import java.util.HashMap;

import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.ArrayItem_;
import kr.co.compcareworker.Data.Company.CompanyData;
import kr.co.compcareworker.Data.Company.Machine.AlMachineDatum;
import kr.co.compcareworker.Data.Company.Machine.MachineItem;
import kr.co.compcareworker.Data.MainViewList.WorkerListData;
import kr.co.compcareworker.Data.PlanDetail.PlanData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ImageListRecyclerAdapter;
import kr.co.compcareworker.Util.Adapter.MachineSubListRecyclerAdapter;
import kr.co.compcareworker.Util.Adapter.WorkerListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

@SuppressLint("ValidFragment")
public class Service_Detail_Fragment extends Fragment implements WorkerListRecyclerAdapter.OnLoadMoreListener {
    private Handler handler, hdr;
    FragmentActivity fa;
    String wr_idx, wo_idx, cp_idx, lineName;

    ArrayItem<PlanData> planDataArrayItem;
    PlanData data;

    ArrayList<String> beforeImageUriArray = new ArrayList<>();
    ArrayList<String> afterImageUriArray = new ArrayList<>();
    ImageListRecyclerAdapter beforeImgAdapter;
    ImageListRecyclerAdapter afterImgAdapter;

    /**
     * 상단정보
     */
    TextView name, office, line, addr, time;
    RecyclerView machineList;
    MachineSubListRecyclerAdapter machineAdapter;
    ArrayItem_<CompanyData> companyItem;

    /**
     * 신청자
     */
    TextView tv_act_service_detail_applicant, tv_act_service_detail_telephone,
            tv_act_service_detail_request_date, tv_act_service_detail_request_time,
            tv_act_service_detail_receipt_content;

    RecyclerView orderImageList;

    /**
     * 기사배정
     */
    TextView tv_act_service_detail_engineer, tv_act_service_detail_engineer_phone,
            tv_act_service_detail_schedule_date, tv_act_service_detail_schedule_time,
            tv_act_service_detail_order_content;
    RecyclerView workImageList;
    LinearLayout arrowFrame;

    /**
     * 일정목록
     */
    TextView planListTitle;
    RecyclerView planList;
    TextView nonePlanList;
    WorkerListRecyclerAdapter planAdapter;
    ArrayList<WorkerListData> planItems;
    ArrayItem<WorkerListData> workerListDataArrayItem;

    int lastIndex = 0, limitCount = 10, count = 0;

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

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

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
        Common.getInstance().currentServiceBeforeImage.clear();
        Common.getInstance().currentServiceAfterImage.clear();
    }

    @SuppressLint("ValidFragment")
    public Service_Detail_Fragment(Handler handler, String wr_idx, String cp_idx, String lineName) {
        this.handler = handler;
        this.wr_idx = wr_idx;
        this.cp_idx = cp_idx;
        this.lineName = lineName;
    }

    public Service_Detail_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_service_detail, container, false);
        /**
         * 상단정보
         */
        name = v.findViewById(R.id.name);
        office = v.findViewById(R.id.office);
        addr = v.findViewById(R.id.addr);
        time = v.findViewById(R.id.time);
        line = v.findViewById(R.id.line);
        machineList = v.findViewById(R.id.machineList);
        machineAdapter = new MachineSubListRecyclerAdapter(getContext(), fa.userItem.getArrayitem().getAgency().getMbId(), fa.userItem.getArrayitem().getMbId(), false);
        machineList.setAdapter(machineAdapter);

        /**
         * 신청자
         */
        tv_act_service_detail_applicant = v.findViewById(R.id.tv_act_service_detail_applicant);
        tv_act_service_detail_telephone = v.findViewById(R.id.tv_act_service_detail_telephone);
        tv_act_service_detail_request_date = v.findViewById(R.id.tv_act_service_detail_request_date);
        tv_act_service_detail_request_time = v.findViewById(R.id.tv_act_service_detail_request_time);
        tv_act_service_detail_receipt_content = v.findViewById(R.id.tv_act_service_detail_receipt_content);
        orderImageList = v.findViewById(R.id.orderImageList);

        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6f, getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity())) - (orderImageList.getPaddingLeft() + orderImageList.getPaddingRight() - px * 6) / 6;
        beforeImgAdapter = new ImageListRecyclerAdapter(getContext(), itemHeight);
        orderImageList.setAdapter(beforeImgAdapter);

        /**
         * 기사배정
         */
        tv_act_service_detail_engineer = v.findViewById(R.id.tv_act_service_detail_engineer);
        tv_act_service_detail_engineer_phone = v.findViewById(R.id.tv_act_service_detail_engineer_phone);
        tv_act_service_detail_schedule_date = v.findViewById(R.id.tv_act_service_detail_schedule_date);
        tv_act_service_detail_schedule_time = v.findViewById(R.id.tv_act_service_detail_schedule_time);
        tv_act_service_detail_order_content = v.findViewById(R.id.tv_act_service_detail_order_content);
        workImageList = v.findViewById(R.id.workImageList);
        arrowFrame = v.findViewById(R.id.arrowFrame);

        itemHeight = (Common.getInstance().getWidth(getActivity())) - (workImageList.getPaddingLeft() + workImageList.getPaddingRight() - px * 6) / 6;
        afterImgAdapter = new ImageListRecyclerAdapter(getContext(), itemHeight);
        workImageList.setAdapter(afterImgAdapter);

        /**
         * 일정목록
         */
        planListTitle = v.findViewById(R.id.planListTitle);
        planList = v.findViewById(R.id.planList);
        nonePlanList = v.findViewById(R.id.nonePlanList);

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

        init_Handler();
        init_Listener();

        planAdapter = new WorkerListRecyclerAdapter(getActivity(), hdr, this, "service");
        planList.setAdapter(planAdapter);

        Get_Top_Contents();
        Get_Contents();

        return v;
    }

    void Get_PlanList() {
        HashMap<String, String> dt = new HashMap<>();
        dt.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        dt.put("cp_idx", data.getWorkData().getCpIdx());
        dt.put("wo_idx", wo_idx);
        dt.put("per_page", limitCount + "");
        dt.put("offset", lastIndex + "");
        new ApiClient(dt, "proc_worker_list", hdr);
    }

    void Get_Top_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("cp_idx", cp_idx);
        new ApiClient(data, "proc_company_view", hdr);
    }

    void Get_Contents() {
        progress.setVisibility(View.VISIBLE);
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("wr_idx", wr_idx);
        Log.d("@@@@@wr체크", "체크");
        new ApiClient(data, "proc_worker_view", hdr);

    }

    void Set_Top_Contents() {
        /** 상단정보*/
        name.setText(companyItem.getArrayitem().getPtName());
        office.setText(companyItem.getArrayitem().getCpName());
        addr.setText(companyItem.getArrayitem().getCpAddr());
        time.setText(companyItem.getArrayitem().getCpRunningTime() + "시간(주" + companyItem.getArrayitem().getCpRunningDay() + "일)");

        line.setText(lineName);

        AlMachineDatum data = null;
        for (AlMachineDatum m : companyItem.getArrayitem().getAlMachineData()) {
            if (m.getMcAirline().equals(lineName)) {
                data = m;
                break;
            }
        }

        ArrayList<MachineItem> item = new ArrayList<>();
        item.addAll(data.getItems());
        machineAdapter.addItem(item);
    }

    void Set_Contents() {
        /** 접수내용*/
        tv_act_service_detail_applicant.setText(data.getWorkData().getWoMan());
        tv_act_service_detail_telephone.setText(data.getWorkData().getWoTel());
        tv_act_service_detail_request_date.setText(data.getWorkData().getWoCalldtDay());
        tv_act_service_detail_request_time.setText(data.getWorkData().getWoCalldtTime());
        tv_act_service_detail_receipt_content.setText(data.getWorkData().getWoMemo());

        if (Common.getInstance().currentServiceBeforeImage != null && Common.getInstance().currentServiceBeforeImage.size() != 0) {
            for (int i = 0; i < Common.getInstance().currentServiceBeforeImage.size(); i++) {
                beforeImageUriArray.add(Common.getInstance().currentServiceBeforeImage.get(i).getUrl());
            }
        }
        beforeImgAdapter.addItem(beforeImageUriArray);
        beforeImgAdapter.itemClick = v -> {
            int position = (int) v.getTag();
            RequestCreator picasso = Picasso.with(getContext()).load(beforeImageUriArray.get(position));
            try {
                picasso.into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        bmp = bitmap;
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                        View view = getLayoutInflater().inflate(R.layout.dlg_image, null);
                        TouchImageView iv = view.findViewById(R.id.imageview);
                        iv.setImageBitmap(bmp);
                        dialogBuilder.setView(view);
                        dialogBuilder.show();
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {

                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });
            } catch (Exception e) {

            }
        };

        /** 레포트등록*/
        tv_act_service_detail_engineer.setText(data.getWrWorkerName());
        tv_act_service_detail_engineer_phone.setText(data.getWrWorkerPhone());
        tv_act_service_detail_schedule_date.setText(data.getWrStartdtDay());
        tv_act_service_detail_schedule_time.setText(data.getWrStartdtTime());
        tv_act_service_detail_order_content.setText(data.getWrMemoReport());

        if (Common.getInstance().currentServiceAfterImage != null && Common.getInstance().currentServiceAfterImage.size() != 0) {
            for (int i = 0; i < Common.getInstance().currentServiceAfterImage.size(); i++) {
                afterImageUriArray.add(Common.getInstance().currentServiceAfterImage.get(i).getUrl());
            }
        }
        afterImgAdapter.addItem(afterImageUriArray);
        afterImgAdapter.itemClick = v -> {
            int position = (int) v.getTag();
            RequestCreator picasso = Picasso.with(getContext()).load(afterImageUriArray.get(position));
            try {
                picasso.into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        bmp = bitmap;
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                        View view = getLayoutInflater().inflate(R.layout.dlg_image, null);
                        TouchImageView iv = view.findViewById(R.id.imageview);
                        iv.setImageBitmap(bmp);
                        dialogBuilder.setView(view);
                        dialogBuilder.show();
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {

                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });
            } catch (Exception e) {

            }
        };

        /**
         * 일정목록
         */

        wo_idx = data.getWoIdx();
        Get_PlanList();
        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_worker_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        planDataArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<PlanData>>() {
                        }.getType());

                        if (planDataArrayItem.isSuccess()) {
                            data = planDataArrayItem.getArrayitem().get(0);
                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), planDataArrayItem.getMessage(), Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        }
                    } else if (url.equals("proc_worker_list")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        workerListDataArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<WorkerListData>>() {
                        }.getType());

                        if (workerListDataArrayItem.isSuccess()) {
                            planList.setVisibility(View.VISIBLE);
                            nonePlanList.setVisibility(View.GONE);

                            planItems = new ArrayList<>();
                            planItems.addAll(workerListDataArrayItem.getArrayitem());
                            count = planItems.size();
                            planListTitle.setText("총 " + count + "건");
                            if (lastIndex != 0) {
                                planAdapter.addItemMore(planItems);
                            } else {
                                planAdapter.addAll(planItems);
                            }
                            planAdapter.itemClick = itemClickListener;
                        } else {
                            //Toast.makeText(getContext(), workerListDataArrayItem.getMessage(), Toast.LENGTH_LONG).show();
                            planList.setVisibility(View.GONE);
                            nonePlanList.setVisibility(View.VISIBLE);
                            planAdapter.clearItem();
                        }
                    } else if (url.equals("proc_company_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        companyItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                        }.getType());

                        if (companyItem.isSuccess()) {
                            Set_Top_Contents();
                        } else {
                            Toast.makeText(getContext(), companyItem.getMessage(), Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        }
                    }
                }
            }
        };
    }

    View.OnClickListener itemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String wr_idx = (String) v.getTag();
            Intent intent = new Intent(getContext(), FragmentActivity.class);
            intent.putExtra("title", "서비스 상세보기");
            intent.putExtra("type", "service_detail");
            intent.putExtra("value1", wr_idx);
            intent.putExtra("value2", cp_idx);
            intent.putExtra("value3", lineName);
            startActivity(intent);
            getActivity().finish();
        }
    };

    private void init_Listener() {
        /** 작업사진 보기*/
        /*img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "작업사진 보기");
                intent.putExtra("type", "shooting");
                intent.putExtra("value1", data.getWoIdx());
                intent.putExtra("value2", data.getWrIdx());
                intent.putExtra("value3", "view");
                startActivity(intent);
            }
        });*/

        /** 거래명세서*/
        arrowFrame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "거래명세표");
                intent.putExtra("type", "deal_list_detail");
                intent.putExtra("value1", data.getInvoiceData().getIvIdx());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onLoadMore(int position) {
        if (count == limitCount) {
            lastIndex += limitCount;
            Get_PlanList();
        }
    }
}
