package kr.co.compcareworker.Fragment.Plan;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

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.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcareworker.Activity.ActivityBasic;
import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.MainActivity;
import kr.co.compcareworker.Activity.WebviewAct;
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.MachineItem;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.Data.MainViewList.WorkerListData;
import kr.co.compcareworker.Data.PlanDetail.PlanData;
import kr.co.compcareworker.Data.PlanDetail.WorkImg.WorkImgData;
import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ContentAdapter;
import kr.co.compcareworker.Util.Adapter.PlanImageRecyclerAdapter;
import kr.co.compcareworker.Util.Adapter.WorkerListRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;
import kr.co.compcareworker.Util.CustomView.CustomDialog;
import kr.co.compcareworker.Util.CustomView.MonitoringDialog;
import kr.co.compcareworker.Util.CustomView.PartnerMemoDialog;
import kr.co.compcareworker.Util.FileUploadHelper;
import kr.co.compcareworker.Util.ServiceThread;

@SuppressLint("ValidFragment")
public class Plan_Detail_Fragment extends Fragment implements WorkerListRecyclerAdapter.OnLoadMoreListener, CompoundButton.OnCheckedChangeListener {
    private Handler handler, hdr, tdr;
    FragmentActivity fa;
    String wr_idx, wo_idx;
    String type;
    ArrayItem<PlanData> planDataArrayItem;
    PlanData data;
    public ArrayList<Uri> imageUriArray;
    CustomDialog dialog;
    ArrayItem<WorkImgData> workImgDataArrayItem;
    Intent intent;
    String memo, result;

    /**
     * 상단정보
     */
    TextView tv_act_plan_detail_name, tv_act_plan_detail_office,
    //            tv_act_plan_detail_corporate_number,
    ll_act_plan_picture_list,
            plan_detail_memo,
            memo_V,
            tv_act_plan_detail_address1,
            tv_act_plan_detail_address2,
            plan_partner_memoTV,
            plan_addr_copyTV;
//            tv_act_plan_detail_ceo,
//            tv_act_plan_detail_responsibility1,
//            tv_act_plan_detail_responsibility2,
//            mae,
//            su,
//            misu;
//            year;

//    LinearLayout maeFrame, suFrame;

    ImageView tv_act_plan_detail_call;
    String call;
    boolean switchCheck = false;
    Button remove;

    /**
     * 매출 내역
     */
    TextView ll_act_enterprise_year_list;

    /**
     * 네비, 보유기종 관리
     */
    TextView tv_act_plan_detail_navigation, tv_act_plan_detail_enterprise_list;

    /**
     * 신청자
     */
//    RelativeLayout viewImage;

    TextView tv_act_plan_detail_receipt_type,
            tv_act_plan_detail_applicant, tv_act_plan_detail_telephone,
            tv_act_plan_detail_request_date, tv_act_plan_detail_request_time,
            tv_act_plan_detail_receipt_content, viewImage;

    /**
     * 기사배정
     */
    RelativeLayout dealList, tv_act_plan_detail_picture, order_edit, check;
    //Switch check;

    TextView tv_act_plan_detail_engineer, tv_act_plan_detail_engineer_phone,
            tv_act_plan_detail_schedule_date, tv_act_plan_detail_schedule_time, tv_act_plan_detail_order_content;


    /**
     * 버튼
     */
    RelativeLayout reWork;
    RelativeLayout tv_act_plan_detail_deal;

    /**
     * 일정목록
     */
    TextView planListTitle;
    //    RecyclerView planList;
//    TextView nonePlanList;
//    WorkerListRecyclerAdapter adapter;
    ArrayList<WorkerListData> items;
    ArrayList<String> imageitems;
    ArrayItem<WorkerListData> workerListDataArrayItem;

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

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

    /**
     * 리사이클러뷰
     */
    RecyclerView receiptImage, workImage_after;
    PlanImageRecyclerAdapter beforeImageAdapter;
    PlanImageRecyclerAdapter afterImageAdapter;
    PlanImageRecyclerAdapter PlanImageadapter;

    /**
     * 명함관리
     */
    TextView enterprise_card_list;

    /**
     * 조치결과 상세증상 2020.05.26
     */
    CheckBox check_01, check_02, check_03, check_04, check_05, check_06,
            check_07, check_08;

    /**
     * 견적서 관리
     **/
    TextView ll_act_enterprise_estimate_list;

    /**
     * 장소수정
     **/
    TextView addr_modifyTV;

    /**
     * 조치결과 메모 저장
     **/
    TextView memo_saveTV;
    boolean memo_save = false;

    /**
     * 기계 목록
     **/
    RecyclerView machine_listRV;
    TextView machine_noneTV;
    ServiceThread thread;
    ContentAdapter machine_adapter;
    LinearLayout machine_listLL;
    int finalPosition;
    int air_line_position;
    ArrayList<MachineItem> machineItems;
    ArrayItem_<CompanyData> machineData;
    Plan_Detail_Fragment.MonitoringServiceHandler holder_hdr;

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

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

    @Override
    public void onStop() {
        super.onStop();
        if (MyApplication.serviceThreads.size() > 0) {
            for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                MyApplication.serviceThreads.get(i).stopForever();
            }
            MyApplication.serviceThreads.clear();
        }
    }


    @SuppressLint("ValidFragment")
    public Plan_Detail_Fragment(Handler handler, String wr_idx, String type) {
        this.handler = handler;
        this.wr_idx = wr_idx;
        this.type = type;
    }

    @SuppressLint("ValidFragment")
    public Plan_Detail_Fragment(Handler handler, String wr_idx, String wo_idx, String type) {
        this.handler = handler;
        this.wr_idx = wr_idx;
        this.wo_idx = wo_idx;
        this.type = type;
    }

    public Plan_Detail_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.frag_plan_detail, container, false);

        /**
         * 상단정보
         */
        tv_act_plan_detail_name = v.findViewById(R.id.tv_act_plan_detail_name);
        tv_act_plan_detail_office = v.findViewById(R.id.tv_act_plan_detail_office);
//        tv_act_plan_detail_corporate_number = v.findViewById(R.id.tv_act_plan_detail_corporate_number);
        tv_act_plan_detail_address1 = v.findViewById(R.id.tv_act_plan_detail_address1);
        tv_act_plan_detail_address2 = v.findViewById(R.id.tv_act_plan_detail_address2);
//        tv_act_plan_detail_ceo = v.findViewById(R.id.tv_act_plan_detail_ceo);
//        tv_act_plan_detail_responsibility1 = v.findViewById(R.id.tv_act_plan_detail_responsibility1);
//        tv_act_plan_detail_responsibility2 = v.findViewById(R.id.tv_act_plan_detail_responsibility2);
        tv_act_plan_detail_call = v.findViewById(R.id.tv_act_plan_detail_call);
        ll_act_plan_picture_list = v.findViewById(R.id.ll_act_plan_picture_list);
//        plan_detail_memo = v.findViewById(R.id.plan_detail_memo);
//        memo_V = v.findViewById(R.id.memo_V);
//        year = v.findViewById(R.id.year);
//        mae = v.findViewById(R.id.mae);
//        su = v.findViewById(R.id.su);
//        misu = v.findViewById(R.id.misu);
//        maeFrame = v.findViewById(R.id.maeFrame);
//        suFrame = v.findViewById(R.id.suFrame);


        /**매출 내역*/
        ll_act_enterprise_year_list = v.findViewById(R.id.ll_act_enterprise_year_list);

        /**
         * 네비, 보유기종 관리
         */
        tv_act_plan_detail_navigation = v.findViewById(R.id.tv_act_plan_detail_navigation);
        tv_act_plan_detail_enterprise_list = v.findViewById(R.id.tv_act_plan_detail_enterprise_list);

        /**
         * 신청자
         */
        viewImage = v.findViewById(R.id.viewImage);

//        tv_act_plan_detail_receipt_type = v.findViewById(R.id.tv_act_plan_detail_receipt_type);
        tv_act_plan_detail_applicant = v.findViewById(R.id.tv_act_plan_detail_applicant);
//        tv_act_plan_detail_telephone = v.findViewById(R.id.tv_act_plan_detail_telephone);
        tv_act_plan_detail_request_date = v.findViewById(R.id.tv_act_plan_detail_request_date);
//        tv_act_plan_detail_request_time = v.findViewById(R.id.tv_act_plan_detail_request_time);
        tv_act_plan_detail_receipt_content = v.findViewById(R.id.tv_act_plan_detail_receipt_content);

        /**
         * 기사배정
         */
//        dealList = v.findViewById(R.id.dealList);
        check = v.findViewById(R.id.check);
//        order_edit = v.findViewById(R.id.order_edit);
        tv_act_plan_detail_picture = v.findViewById(R.id.tv_act_plan_detail_picture);
        tv_act_plan_detail_engineer = v.findViewById(R.id.tv_act_plan_detail_engineer);
        //tv_act_plan_detail_engineer_phone = v.findViewById(R.id.tv_act_plan_detail_engineer_phone);
        tv_act_plan_detail_schedule_date = v.findViewById(R.id.tv_act_plan_detail_schedule_date);
        tv_act_plan_detail_schedule_time = v.findViewById(R.id.tv_act_plan_detail_schedule_time);
        tv_act_plan_detail_order_content = v.findViewById(R.id.tv_act_plan_detail_order_content);

        /** 버튼*/
        reWork = v.findViewById(R.id.reWork);
        tv_act_plan_detail_deal = v.findViewById(R.id.tv_act_plan_detail_deal);

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

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

        /** 리사이클러뷰*/
        imageUriArray = new ArrayList<>();
        receiptImage = v.findViewById(R.id.receiptImage);
        workImage_after = v.findViewById(R.id.workImage_after);
        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity())) - (receiptImage.getPaddingLeft() + receiptImage.getPaddingRight() - px * 6) / 5;
        beforeImageAdapter = new PlanImageRecyclerAdapter(getActivity(), itemHeight, "hide", "");
        afterImageAdapter = new PlanImageRecyclerAdapter(getActivity(), itemHeight);
        receiptImage.setAdapter(beforeImageAdapter);
        workImage_after.setAdapter(afterImageAdapter);

        /**명함관리*/
        enterprise_card_list = v.findViewById(R.id.enterprise_card_list);

        /**비고란**/
        plan_partner_memoTV = v.findViewById(R.id.plan_partner_memoTV);

        /**견적서 관리**/
        ll_act_enterprise_estimate_list = v.findViewById(R.id.ll_act_enterprise_estimate_list);

        /**주소 복사**/
        plan_addr_copyTV = v.findViewById(R.id.plan_addr_copyTV);

        /**조치결과 체크박스*/
        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);

        CheckBox[] checked = {check_01, check_02, check_03, check_04, check_05, check_06, check_07, check_08};

        for (int i = 0; i < checked.length; i++) {

            checked[i].setOnCheckedChangeListener(this);
        }

        /**장소 수정**/
        addr_modifyTV = v.findViewById(R.id.addr_modifyTV);

        /**조치결과 메모 저장**/
        memo_saveTV = v.findViewById(R.id.memo_saveTV);

        /**기계 목록**/
        machine_listRV = v.findViewById(R.id.machine_listRV);
        machine_noneTV = v.findViewById(R.id.machine_noneTV);
        machine_listLL = v.findViewById(R.id.machine_listLL);

        init_Handler();
        init_Listener();
        init_Transfer();
        Get_Contents();

        ll_act_plan_picture_list.setText(Html.fromHtml("서비스 <b>  사진</b>"));

        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        afterImageAdapter.setOnItemClickListener(new PlanImageRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Log.e("PlanImageAdapter", "PlanImageRecyclerAdapter");
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("삭제하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {

                        afterImageAdapter.removeItem(position);
                        HashMap<String, String> data = new HashMap<>();
                        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                        data.put("wo_idx", wo_idx);
                        data.put("wr_idx", wr_idx);
                        data.put("type", "delete");
                        data.put("index", "" + position);
                        data.put("mb_id", Common.getInstance().getPref(getContext(), "id"));

                        new ApiClient(data, "proc_work_photo_write", tdr);
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });

    }

    void Get_Company() {

        if (fa == null) {
            fa = (FragmentActivity) getActivity();
        }

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

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

    public void Get_Contents() {
        //progress.setVisibility(View.VISIBLE);
        if (fa == null) {
            fa = (FragmentActivity) getActivity();
        }

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("wr_idx", wr_idx);
        new ApiClient(data, "proc_worker_view", hdr);
    }


    void Get_Contents_file() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("wr_idx", wr_idx);
        data.put("wo_idx", wo_idx);
        data.put("file_type", "after");
        new ApiClient(data, "proc_worker_file", tdr);

        Log.e("Get_Contents_file", data.toString());
    }

    void Set_Contents() {

        /** 상단정보*/
        tv_act_plan_detail_name.setText(data.getCuName());
        tv_act_plan_detail_office.setText(data.getCpName());
//        tv_act_plan_detail_corporate_number.setText(data.getWorkData().getCuCode());
        tv_act_plan_detail_address1.setText(data.getWorkData().getCpAddr());
        tv_act_plan_detail_address2.setText(data.getWorkData().getCpAddrSub());

//        tv_act_plan_detail_ceo.setText(Common.getInstance().isNull(data.getWorkData().getCuCeo()).toString());
//        tv_act_plan_detail_responsibility1.setText(Common.getInstance().isNull(data.getWorkData().getCuMan()).toString());
//        tv_act_plan_detail_responsibility2.setText(Common.getInstance().isNull(data.getWorkData().getPtManSub()).toString());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy년");
        Calendar cal = Calendar.getInstance();
//        year.setText(sdf.format(cal.getTime()));

//        misu.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(data.getWorkData().getPtSellwillMoney())) + "원");
//        if (!TextUtils.isEmpty(fa.userItem.getArrayitem().getMbType2()) && fa.userItem.getArrayitem().getMbType2().equals("eng")) {
//            maeFrame.setVisibility(View.GONE);
//            suFrame.setVisibility(View.GONE);
//        } else {
//            mae.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(data.getWorkData().getPtSellMoney())) + "원");
//            su.setText(Common.getInstance().moneyFormatToWon(Integer.parseInt(data.getWorkData().getPtSellokMoney())) + "원");
//        }

//        /**2020-05-15 수정. 메모 유무 v표시로 표현*/
//        if (!TextUtils.isEmpty(data.getWrMemoReport()) || data.getWrMemoReport() != null) {
//
//            memo_V.setVisibility(View.VISIBLE);
//
//        } else {
//            memo_V.setVisibility(View.GONE);
//        }

        /** 전화버튼*/
        call = data.getWorkData().getWoTel();

        /** 신청자*/
//        tv_act_plan_detail_receipt_type.setText(data.getWorkData().getWoTypeStr());
        tv_act_plan_detail_applicant.setText(data.getWorkData().getWoMan());
//        tv_act_plan_detail_telephone.setText(data.getWorkData().getWoTel());
        tv_act_plan_detail_request_date.setText(data.getWorkData().getWoCalldtDay());
//        tv_act_plan_detail_request_time.setText(data.getWorkData().getWoCalldtTime());
        tv_act_plan_detail_receipt_content.setText(data.getWorkData().getWoMemo());

        /** 기사배정*/
        tv_act_plan_detail_engineer.setText(data.getWrWorkerName());
        //tv_act_plan_detail_engineer_phone.setText(data.getWrWorkerPhone());
        tv_act_plan_detail_schedule_date.setText(data.getWrStartdtDay());
        tv_act_plan_detail_schedule_time.setText(data.getWrStartdtTime());
        tv_act_plan_detail_order_content.setText(data.getWrMemoReport());
//        if (data.getWorkData().getWoWorkerCheck().equals("Y")) {
//            switchCheck = true;
//            check.setChecked(true);
//        }

        /** 사진*/
        beforeImageAdapter.clearItem();
        afterImageAdapter.clearItem();
        ArrayList<String> before = new ArrayList<>();
        ArrayList<String> after = new ArrayList<>();
        if (data.getWorkData().getFileDataBefore() != null) {
            for (int i = 0; i < data.getWorkData().getFileDataBefore().size(); i++) {
                before.add(data.getWorkData().getFileDataBefore().get(i).getUrl());
            }
            Log.e("before", before.toString());
            beforeImageAdapter.addItem(before);
        }

        if (data.getWorkData().getFileDataAfter() != null) {
            loop:
            for (int i = 0; i < data.getWorkData().getFileDataAfter().size(); i++) {
                if (wr_idx.equals(data.getWorkData().getFileDataAfter().get(i).getWrIdx())) {
                    for (int j = 0; j < data.getWorkData().getFileDataAfter().get(i).getItems().size(); j++) {
                        after.add(data.getWorkData().getFileDataAfter().get(i).getItems().get(j).getUrl());
                    }
                    break loop;
                }
            }
            Log.e("after", after.toString());
            afterImageAdapter.addItem(after);
        }


        /**조치결과 퀵메뉴 셀렉트 상태*/
        CheckBox[] checked = {check_01, check_02, check_03, check_04, check_05, check_06, check_07, check_08};
        String[] memo_txt = {"소모품 교환", "쿨러 교환", "전장품 교환", "오일 보충", "기계수리 완료", "기계설치 완료", "점검 완료", "기타"};
        String memo_sub = data.getWrMemoReportSub();

        if (!TextUtils.isEmpty(memo_sub)) {
            for (int i = 0; i < checked.length; i++) {
                checked[i].setOnCheckedChangeListener(null);
                if (memo_sub.contains(memo_txt[i])) {
                    checked[i].setChecked(true);
                }
                checked[i].setOnCheckedChangeListener(this);
            }
        } else {

            checked[6].setChecked(true);
        }

        wo_idx = data.getWoIdx();
        Get_Company();
//        Get_PlanList();
        MyApplication.uploadFinish = true;
    }

    // 체크박스를 클릭해서 상태가 바꾸었을 경우 호출되는 콜백 메서드
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        result = "";
        memo = data.getWrMemoReport();
        CheckBox[] checked = {check_01, check_02, check_03, check_04, check_05, check_06, check_07, check_08};
        for (int i = 0; i < checked.length; i++) {
            if (checked[i].isChecked()) {
                result = result + "(" + checked[i].getText().toString() + ")";
            }
        }

        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("wr_idx", wr_idx);
        data.put("mb_id", fa.userItem.getArrayitem().getMbId());
        data.put("wr_memo_report_sub", result);

        if (!TextUtils.isEmpty(memo)) {

            data.put("wr_memo_report", memo);
        }

        new ApiClient(data, "proc_worker_edit", hdr);
    }

    void start_thread(int start, int end) {

        if (start != air_line_position) {

            if (MyApplication.serviceThreads.size() > 0) {
                for (int i = 0; i < MyApplication.serviceThreads.size(); i++) {
                    MyApplication.serviceThreads.get(i).stopForever();
                }
                MyApplication.serviceThreads.clear();
            }

            for (int i = start; i <= end; i++) {
                if (machineItems.get(i).getMcIotMac() != null) {
                    ServiceThread thread = new ServiceThread(holder_hdr, "monitoring", machineItems.get(i).getMcIotMac(), i + "");
                    MyApplication.serviceThreads.add(thread);
                    thread.start();
                }
            }

            air_line_position = start;
        }
    }

    class MonitoringServiceHandler extends Handler {
        @Override
        public void handleMessage(android.os.Message msg) {

            String msg_data = msg.obj.toString();
            String get_mac = msg_data.substring(0, msg_data.indexOf("i"));
            String i = msg_data.substring(msg_data.indexOf("i") + 1);

            MyApplication.stop_ui_change = true;

            HashMap<String, String> data = new HashMap<>();
            data.put("mac", get_mac);
            data.put("i", i);
            new ApiClient(data, "proc_monitoring", hdr);
        }
    }


    public 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_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_SHORT).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);
//
//                            items = new ArrayList<>();
//                            items.addAll(workerListDataArrayItem.getArrayitem());
//                            count = items.size();
//                            planListTitle.setText("총 " + count + "건");
//                            if (lastIndex != 0) {
//                                adapter.addItemMore(items);
//                            } else {
//                                adapter.addAll(items);
//                            }
//                            adapter.itemClick = itemClickListener;
//                        } else {
//                            if (lastIndex == 0) {
//                                planList.setVisibility(View.GONE);
//                                nonePlanList.setVisibility(View.VISIBLE);
//                                adapter.clearItem();
//                            }
//                        }
                    } else if (url.equals("proc_worker_edit")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

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

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {

                            if (memo_save) {
                                Toast.makeText(getContext(), "저장되었습니다.", Toast.LENGTH_SHORT).show();
                                memo_save = false;
                            }

                            if (dialog != null) {
                                tv_act_plan_detail_order_content.setText(dialog.con);
                                dialog.dismiss();
                            }
                        }

                    } else if (url.equals("proc_company_view")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        fa.enterpriseItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem_<CompanyData>>() {
                        }.getType());

                        if (!fa.enterpriseItem.isSuccess()) {
                            Toast.makeText(getContext(), fa.enterpriseItem.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }

                        if (fa.enterpriseItem.getArrayitem().getAlMachineData().size() > 0) {
                            /** 어댑터 세팅*/
                            machineItems = new ArrayList<>();

                            for (int i = 0; i < fa.enterpriseItem.getArrayitem().getAlMachineData().size(); i++) {
                                machineItems.addAll(fa.enterpriseItem.getArrayitem().getAlMachineData().get(i).getItems());
                            }

                            String cp_air_line = fa.enterpriseItem.getArrayitem().getCpAirline().toString();
                            String[] air_lines = cp_air_line.split(",");

                            for (String air_line : air_lines) {

                                int cnt = 1;

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

                                    if (machineItems.get(i).getMcAirline().equals(air_line)) {
                                        machineItems.get(i).setIndex(cnt);

                                        if (cnt == 1) {
                                            machineItems.get(i).setShow_position(true);
                                            machineItems.get(i).setLast_position(true);

                                        } else if (cnt > 1) {
                                            machineItems.get(i - 1).setLast_position(false);
                                            machineItems.get(i).setLast_position(true);
                                        }
                                        cnt++;
                                    }
                                }
                            }

                            machine_adapter = new ContentAdapter(getContext(),/* new ContentAdapter.optionListener() {
                                @Override
                                public void clickBtn(Bundle bundle) {
                                    Intent intent = new Intent(getContext(), FragmentActivity.class);
                                    intent.putExtra("title", "기계 옵션설정");
                                    intent.putExtra("type", "machine_option");
                                    intent.putExtra("value1", bundle.getString("mc_idx"));
                                    startActivity(intent);
                                }
                            }, */new ContentAdapter.chartClickListener() {
                                @Override
                                public void clickBtn(Bundle bundle) {

                                    String mc_idx = bundle.getString("mc_idx");
                                    String mac = bundle.getString("mac");
                                    MachineItem machineItem = null;

                                    for (int i = 0; i < machineItems.size(); i++) {
                                        if (machineItems.get(i).getMcIdx().equals(mc_idx)) {
                                            machineItem = machineItems.get(i);
                                        }
                                    }

                                    if (TextUtils.isEmpty(mac) || mac.equals("0")) {
                                        Toast.makeText(getContext(), "연결된 IoT 기기가 없습니다.", Toast.LENGTH_SHORT).show();

                                    } else {

                                        MonitoringDialog dialog = new MonitoringDialog(getContext(), fa.userItem.getArrayitem().getAgIdx(), bundle.getString("pt_idx"), bundle.getString("cp_idx"),
                                                mc_idx, bundle.getString("chart_type"), mac, machineItem);
                                        dialog.show();
                                    }
                                }
                            });

                            machine_listRV.setAdapter(machine_adapter);
                            machine_adapter.addItem(machineItems);

                            //메인화면 로딩시 첫번째 아이템이 mac주소가 있으면 데이터를 가져온다.
                            holder_hdr = new Plan_Detail_Fragment.MonitoringServiceHandler();

                            if (machineItems.size() > 0) {

                                if (thread != null) {
                                    thread.stopForever();
                                    thread = null;
                                }

                                int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
                                for (int i = 0; i < machineItems.size(); i++) {
                                    if (machineItems.get(i).getMcIotMac() != null) {
                                        if (machineItems.size() > 4) {
                                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150 * px);
                                            machine_listLL.setLayoutParams(lp);
                                            break;
                                        } else {
                                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                            machine_listLL.setLayoutParams(lp);
                                            break;
                                        }

                                    } else {
                                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                        machine_listLL.setLayoutParams(lp);
                                    }
                                }

                            } else {
                                machine_listRV.setVisibility(View.GONE);
                                machine_noneTV.setVisibility(View.VISIBLE);
                            }

                            RecyclerView.ItemAnimator animator = machine_listRV.getItemAnimator();
                            if (animator instanceof SimpleItemAnimator) {
                                ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
                            }
                            air_line_position = -1;
                            machine_listRV.setItemViewCacheSize(machineItems.size());
                            machine_listRV.addOnScrollListener(new RecyclerView.OnScrollListener() {
                                @Override
                                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                                }

                                @Override
                                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                                    super.onScrolled(recyclerView, dx, dy);
                                    LinearLayoutManager layoutManager = ((LinearLayoutManager) recyclerView.getLayoutManager());
                                    int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
                                    int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
                                    start_thread(firstVisiblePosition, lastVisiblePosition);
                                }
                            });

                        } else {
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            machine_listLL.setLayoutParams(lp);
                            machine_listRV.setVisibility(View.GONE);
                            machine_noneTV.setVisibility(View.VISIBLE);
                        }
                    }
                    if (url.equals("proc_monitoring")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        ArrayItem<MonitoringData> monitoringArray;
                        monitoringArray = new Gson().fromJson(result_item, new TypeToken<ArrayItem<MonitoringData>>() {
                        }.getType());

                        int position = Integer.parseInt(result_item.get("resultItem").getAsJsonObject().get("message").getAsString());

                        //모니터링 데이터를 정상적으로 가져왔을 때
                        if (monitoringArray.isSuccess()) {
                            machineItems.get(position).setRunning(true);
                            machineItems.get(position).setMonitoring(monitoringArray);
                            machine_adapter.notifyItemChanged(position, null);

                            MyApplication.stop_ui_change = false;
                        }
                        //모니터링 데이터를 가져오는 것을 실패했을 때
                        else {

                            machineItems.get(position).setRunning(true);
                            machineItems.get(position).setMonitoring(null);
                            machine_adapter.notifyItemChanged(position, null);

                            MyApplication.stop_ui_change = false;
                        }
                    }
                } else if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }
            }
        };
    }

    public void init_Transfer() {
        tdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                Log.e("tdr", tdr.toString());
                Log.e("msg", msg.toString());

                String url2 = msg.getData().getString("url");
                if (msg.what == 1) {

                    if (url2.equals("proc_worker_file")) {
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        workImgDataArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<WorkImgData>>() {
                        }.getType());

                        if (workImgDataArrayItem.isSuccess()) {
                            items = new ArrayList<>();

                            for (int i = 0; i < workImgDataArrayItem.getArrayitem().size(); i++) {
                                imageitems.add(workImgDataArrayItem.getArrayitem().get(i).getUrl());
                                new Plan_Detail_Fragment.ImageDownload(workImgDataArrayItem.getArrayitem().get(i).getPfiFilename().split("\\.")[0])
                                        .execute(workImgDataArrayItem.getArrayitem().get(i).getUrl());
                            }
                            PlanImageadapter.addItem(imageitems);
                        }
                        progress.setVisibility(View.GONE);
                    } else if (url2.equals("proc_work_photo_write")) {

                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
                            Intent intent = new Intent();
                            getActivity().setResult(Activity.RESULT_OK, intent);
                            Get_Contents();

                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_SHORT).show();
                            MyApplication.uploadError = true;
                        }
                    }
                } else if (msg.what == -1) {

                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                }

            }
        };
    }

    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", "plan_detail");
            intent.putExtra("value1", wr_idx);

            startActivity(intent);
            getActivity().finish();
        }
    };

    private void init_Listener() {

        /** 네비게이션 연결*/
        tv_act_plan_detail_navigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //우편번호가 없을 때
                if (data.getWorkData().getCpZip() == null || data.getWorkData().getCpZip().equals("") ||
                        data.getWorkData().getCpMapx() == null || data.getWorkData().getCpMapx().equals("") ||
                        data.getWorkData().getCpMapy() == null || data.getWorkData().getCpMapy().equals("")) {

                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("우편번호 혹은 주소가 잘못되어 연결이 불가합니다.\n주소를 복사하여 외부 네비게이션을 사용해주세요.");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();

                } else {
                    Common.getInstance().navigationDialog(getContext(), fa.enterpriseItem.getArrayitem().getPtName(), Double.parseDouble(fa.enterpriseItem.getArrayitem().getCpMapy()), Double.parseDouble(fa.enterpriseItem.getArrayitem().getCpMapx()));
                }
            }
        });


        /** 메모 다이얼로그 */
        /* 21.06.28 메모 다이얼로그 대신 화면에 바로 보이는 형식으로 수정 요청.
        plan_detail_memo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String memo_sub = data.getWrMemoReportSub();

                CustomDialog customDialog = new CustomDialog(getContext(), data.getWrMemoReport(), new CustomDialog.CustomDialogListener() {
                    @Override
                    public void clickBtn(String getData) {

                        HashMap<String, String> data = new HashMap<>();
                        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                        data.put("wr_idx", wr_idx);
                        data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                        data.put("wr_memo_report", getData);

                        if (!TextUtils.isEmpty(memo_sub)) {

                            data.put("wr_memo_report_sub", memo_sub);

                        } else {

                            data.put("wr_memo_report_sub", "(점검 완료)");
                        }
                        new ApiClient(data, "proc_worker_edit", hdr);
                    }
                });
                customDialog.show();
            }
        });
        */
        //21.07.14 메모를 계속 추가해서 쓰기 때문에 저장버튼 추가 요청.
        memo_saveTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                memo_save = true;
                result = "";
                CheckBox[] checked = {check_01, check_02, check_03, check_04, check_05, check_06, check_07, check_08};
                for (int i = 0; i < checked.length; i++) {
                    if (checked[i].isChecked()) {
                        result = result + "(" + checked[i].getText().toString() + ")";
                    }
                }

                HashMap<String, String> data = new HashMap<>();
                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                data.put("wr_idx", wr_idx);
                data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                data.put("wr_memo_report", tv_act_plan_detail_order_content.getText().toString());

                if (!TextUtils.isEmpty(result)) {
                    data.put("wr_memo_report_sub", result);

                } else {
                    data.put("wr_memo_report_sub", "(점검 완료)");
                }

                new ApiClient(data, "proc_worker_edit", hdr);
            }
        });


        /** 담당자 전화연결*/
        tv_act_plan_detail_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(call) || call.equals("")) {
                    Toast.makeText(getContext(), "전화번호가 없습니다.", Toast.LENGTH_LONG).show();
                    return;
                }
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("전화연결 하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        try {
                            Uri uri = Uri.parse("tel:" + call);
                            getContext().startActivity(new Intent("android.intent.action.DIAL", uri));
                            dialog.dismiss();
                        } catch (Exception e) {
                            Toast.makeText(getContext(), "전화번호 형식이 올바르지 않습니다.", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });

        /**명함관리 2020-06-03*/
        enterprise_card_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "명함 관리");
                intent.putExtra("type", "business_card_management");
                intent.putExtra("value1", data.getCpIdx());

                startActivity(intent);
            }
        });


        /** 사진 촬영 */

        tv_act_plan_detail_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

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

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

                                HashMap<String, String> data = new HashMap<>();
                                data.put("ag_idx", ActivityBasic.userItem.getArrayitem().getAgIdx());
                                data.put("wo_idx", wo_idx);
                                data.put("wr_idx", wr_idx);
                                data.put("mb_id", Common.getInstance().getPref(requireContext(), "id"));

                                MyApplication.uploadFinish = false;

                                new ApiClient(getContext(), data, "proc_work_photo_write", imageUriArray, tdr);
                            });

//                    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);
//
//                            ArrayList<String> arr = new ArrayList<>();
//                            for (int i = 0; i < uriList.size(); i++) {
//                                arr.add(uriList.get(i).toString());
//                            }
//
//                            HashMap<String, String> data = new HashMap<>();
//                            data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
//                            data.put("wo_idx", wo_idx);
//                            data.put("wr_idx", wr_idx);
//                            data.put("mb_id", Common.getInstance().getPref(getContext(), "id"));
//
//                            MyApplication.uploadFinish = false;
//
//                            new ApiClient(getContext(), data, "proc_work_photo_write", imageUriArray, tdr);
//
//                        }
//                    })
//                            .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();
                }
            }
        });


        /** A/S 완료*/
        tv_act_plan_detail_deal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HashMap<String, String> save_data = new HashMap<>();
                save_data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                save_data.put("wr_idx", wr_idx);
                save_data.put("mb_id", fa.userItem.getArrayitem().getMbId());

                if (TextUtils.isEmpty(result)) {

                    save_data.put("wr_memo_report_sub", "(점검 완료)");
                } else {

                    save_data.put("wr_memo_report_sub", result);
                }

                save_data.put("wr_memo_report", tv_act_plan_detail_order_content.getText().toString());

                new ApiClient(save_data, "proc_worker_edit", hdr);

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "A/S 완료");
                intent.putExtra("type", "deal");
                intent.putExtra("value1", data.getInvoiceData().getIvIdx());
                intent.putExtra("value2", data.getWorkData().getWoIotMac());
                startActivityForResult(intent, 100);
            }
        });

        /** 보유기종관리*/
        tv_act_plan_detail_enterprise_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "보유기종 관리");
                intent.putExtra("type", "machine");
                intent.putExtra("value1", data.getWorkData().getPtIdx());
                startActivity(intent);
            }
        });

        /** 접수사진 보기*/
        viewImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "접수사진 보기");
                intent.putExtra("type", "before");
                intent.putExtra("value1", data.getWrIdx());
                intent.putExtra("value2", data.getWoIdx());
                startActivity(intent);
            }
        });

        /**매출 내역*/
        ll_act_enterprise_year_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String incodeUrl = URLEncoder.encode("https://" + fa.userItem.getArrayitem().getAgency().getMbId() +
                        ".compcare.co.kr/sell/invoice/invoice_total_item/?ag_idx=" + data.getInvoiceData().getAgIdx() + "&cp_idx=" + data.getInvoiceData().getCpIdx() + "&pt_idx=" + data.getInvoiceData().getPtIdx());
                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);
            }
        });

        /**서비스 사진**/
        ll_act_plan_picture_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "서비스 사진");
                intent.putExtra("type", "service_image");
                intent.putExtra("value1", data.getAgIdx());
                intent.putExtra("value2", data.getWorkData().getPtIdx());
                startActivity(intent);
            }
        });


        /** 거래명세서*/
//        dealList.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);
//            }
//        });

//        /** 서비스 재등록*/
//        reWork.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/" + data.getWoIdx() + "?rewrite=Y");
//                Intent intent = new Intent(getContext(), WebviewAct.class);
//                intent.putExtra("title", "서비스 재등록");
//                intent.putExtra("url", "https://" + fa.userItem.getArrayitem().getAgency().getMbId() + ".compcare.co.kr/api/web/engineer/?url=" + incodeUrl);
//                startActivity(intent);
//            }
//        });

        /**거래명세표 관리(수정,등록)*/

        reWork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "거래명세표 수정/등록");
                intent.putExtra("type", "Invoice_management");
                intent.putExtra("value1", data.getInvoiceData().getIvIdx());
                startActivity(intent);
            }
        });


        /** 조치결과 등록/수정 */
//        order_edit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                /*dialog = new CustomDialog(getActivity(),
//                        hdr,
//                        tv_act_plan_detail_order_content.getText().toString(),
//                        fa.userItem.getArrayitem().getAgIdx(),
//                        wr_idx,
//                        fa.userItem.getArrayitem().getMbId());
//                dialog.show();*/
//                HashMap<String, String> data = new HashMap<>();
//                data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
//                data.put("wr_idx", wr_idx);
//                data.put("mb_id", fa.userItem.getArrayitem().getMbId());
//                data.put("wr_memo_report", tv_act_plan_detail_order_content.getText().toString());
//                new ApiClient(data, "proc_worker_edit", hdr);
//            }
//        });


        /** 배정확인*/
//        check.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            if (switchCheck) {
//                switchCheck = false;
//            } else {
//                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
//                dialog.setTitle(R.string.app_name);
//                dialog.setCancelable(false);
//                String message = isChecked ? "배정확인 하시겠습니까?" : "배정취소 하시겠습니까?";
//                dialog.setMessage(message);
//                dialog.setPositiveButton("확인", (dialog1, which) -> {
//                    HashMap<String, String> data = new HashMap<>();
//                    data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
//                    data.put("wr_idx", wr_idx);
//                    data.put("mb_id", fa.userItem.getArrayitem().getMbId());
//                    data.put("wr_check", isChecked ? "Y" : "N");
//                    new ApiClient(data, "proc_worker_edit", hdr);
//                    dialog1.dismiss();
//                });
//
//                dialog.setNegativeButton("취소", (dialog2, which) -> {
//                    switchCheck = true;
//                    check.setChecked(!check.isChecked());
//                    dialog2.dismiss();
//                });
//                dialog.show();
//            }
//        });

        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                dialog.setTitle(R.string.app_name);
                dialog.setCancelable(false);

                boolean workerChecked = false;
                if (data.getWorkData().getWoWorkerCheck().equals("Y")) {
                    workerChecked = true;
                }

                String message = workerChecked ? "배정취소 하시겠습니까?" : "배정확인 하시겠습니까?";
                dialog.setMessage(message);

                boolean finalWorkerChecked = workerChecked;
                String memo_sub = data.getWrMemoReportSub();
                String memo = data.getWrMemoReport();

                dialog.setPositiveButton("확인", (dialog1, which) -> {
                    HashMap<String, String> data = new HashMap<>();
                    data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                    data.put("wr_idx", wr_idx);
                    data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                    data.put("wr_check", finalWorkerChecked ? "N" : "Y");

                    if (!TextUtils.isEmpty(memo)) {

                        data.put("wr_memo_report", memo);
                    }

                    if (!TextUtils.isEmpty(memo_sub)) {

                        data.put("wr_memo_report_sub", memo_sub);
                    }

                    new ApiClient(data, "proc_worker_edit", hdr);
                    dialog1.dismiss();
                });

                dialog.setNegativeButton("취소", (dialog2, which) -> {
                    dialog2.dismiss();
                });
                dialog.show();

            }
        });

        /**비고란**/
        plan_partner_memoTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String partner_memo = data.getWorkData().getPtMemo();
                String partner_name = data.getWorkData().getPtName();

                PartnerMemoDialog dialog = new PartnerMemoDialog(getContext(), partner_name, partner_memo, data.getWorkData().getPtIdx(), new PartnerMemoDialog.PartnerMemoDialogListener() {
                    @Override
                    public void clickBtn() {

                        Get_Contents();
                    }
                });
                dialog.show();
            }
        });

        /**견적서 관리**/

        ll_act_enterprise_estimate_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "견적서 관리");
                intent.putExtra("type", "estimate_list");
                intent.putExtra("value1", fa.enterpriseItem.getArrayitem().getAgIdx());
                intent.putExtra("value2", fa.enterpriseItem.getArrayitem().getCpIdx());
                startActivity(intent);
            }
        });

        /**주소복사**/
        plan_addr_copyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("copy_addr", tv_act_plan_detail_address1.getText());
                clipboard.setPrimaryClip(clipData);
                Toast.makeText(getContext(), "주소가 복사되었습니다.", Toast.LENGTH_SHORT).show();
            }
        });

        /**장소수정**/
        addr_modifyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), FragmentActivity.class);
                intent.putExtra("title", "장소 정보 수정");
                intent.putExtra("type", "place_adjust3");
                intent.putExtra("value1", wo_idx);
                intent.putExtra("value2", "");
                getContext().startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (thread != null) thread.stopForever();
        Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
    }

    private class ImageDownload extends AsyncTask<String, Integer, Void> {
        /**
         * 파일명
         */
        private String fileName;
        /**
         * 저장할 폴더
         */
        private final String SAVE_FOLDER = "/CompcareWorker";

        public ImageDownload(String fileName) {
            this.fileName = fileName.substring(8, fileName.length() - 1);
        }

        @Override
        protected Void doInBackground(String... params) {
            //다운로드 경로를 지정
            //String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + SAVE_FOLDER;
            String savePath = Environment.getExternalStorageDirectory() + "/DCIM" + SAVE_FOLDER;
            File dir = new File(savePath);
            //상위 디렉토리가 존재하지 않을 경우 생성
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //웹 서버 쪽 파일이 있는 경로
            String fileUrl = params[0];
            //다운로드 폴더에 동일한 파일명이 존재하는지 확인
//            if (new File(savePath + "/" + fileName).exists() == false) {
//
//            } else {
//
//            }

            String localPath = Environment.getExternalStorageDirectory() + "/DCIM" + SAVE_FOLDER + "/" + fileName + ".jpg";
            try {
                URL imgUrl = new URL(fileUrl);
                //서버와 접속하는 클라이언트 객체 생성
                HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
                int len = conn.getContentLength();
                byte[] tmpByte = new byte[len];
                //입력 스트림을 구한다
                InputStream is = conn.getInputStream();
                File file = new File(localPath);
                file.createNewFile();

                //파일 저장 스트림 생성
                FileOutputStream fos = new FileOutputStream(file);
                int read;
                //입력 스트림을 파일로 저장
                for (; ; ) {
                    read = is.read(tmpByte);
                    if (read <= 0) {
                        break;
                    }
                    fos.write(tmpByte, 0, read); //file 생성
                }
                is.close();
                fos.close();
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            String targetDir = Environment.getExternalStorageDirectory() + "/DCIM" + SAVE_FOLDER;
            File file = new File(targetDir + "/" + fileName + ".jpg");
            imageUriArray.add(Uri.fromFile(file));
        }
    }

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                getActivity().finish();

            }
        }
    }
}
