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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
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.telephony.PhoneNumberFormattingTextWatcher;
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.Button;
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.ProgressBar;
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.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
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.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.Engineer.EngineerData;
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.R;
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.FileUploadHelper;

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


    FragmentActivity fa;
    Handler handler, tdr, hdr;
    public ArrayList<Uri> imageUriArray;
    String cp_idx, wr_idx, wo_idx;
    ArrayItem<WorkerListData> workerListDataArrayItem;
    ArrayItem_<WorkerListData> items;
    ArrayList<WorkerListData> item;
    ArrayItem<PlanData> planDataArrayItem;
    PlanData data;
    int lastIndex = 0, limitCount = 10, count = 0;
    WorkerListRecyclerAdapter adapter;
    ArrayItem<WorkImgData> workImgDataArrayItem;
    ArrayList<String> imageitems;
    ArrayList<String> arr = new ArrayList<>();


    /**
     * 신청자 정보
     */
    EditText sv_register_nameTV, sv_register_telTV;

    /**
     * 사진관련
     */
    RelativeLayout service_register_btn;
    LinearLayout tv_act_service_picture;

    /**
     * 달력
     */
    Button date_picker;
    TextView picker_text;

    /**
     * 회사 정보
     */
    TextView tv_act_service_address1, tv_act_service_address2, tv_act_service_ceo, tv_act_service_name,
            tv_act_service_office;

    /**
     * 프리퍼런스
     */

    /**
     * 상세증상
     */
    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;

    /**
     * 방문기사
     */
    RadioGroup engineerRG;
    LinearLayout engineerLL;
    HorizontalScrollView scrollView;

    ArrayItem<EngineerData> engineer_array;
    EngineerData engineer_data;
    String[] engineer_id;
    String select_engineer_id;
    String engineer_name;
    /**
     * 방문시간
     */
    RadioButton radio_01, radio_02, radio_03, radio_04, radio_05, radio_06, radio_07, radio_08, radio_09,
            radio_10, radio_11, radio_12, radio_13, radio_14, radio_15, radio_16, radio_17, radio_18, radio_19, radio_20, radio_21, radio_22, radio_23;

    HorizontalScrollView time_SV;

    /**
     * 리사이클러뷰
     */
    RecyclerView workImage;
    PlanImageRecyclerAdapter Adapter;


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

    private DatePickerDialog.OnDateSetListener callbackMethod;

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

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

    @Override
    public void onResume() {
        super.onResume();
        //Get_Contents();
        Get_Company();
        init_Listener();

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

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

    public Service_Register_Fragment() {
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_service_register, container, false);

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

        /**방문기사*/
        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);

        /**방문시간*/
        time_SV = v.findViewById(R.id.time_SV);

        radio_01 = v.findViewById(R.id.radio_01);
        radio_02 = v.findViewById(R.id.radio_02);
        radio_03 = v.findViewById(R.id.radio_03);
        radio_04 = v.findViewById(R.id.radio_04);
        radio_05 = v.findViewById(R.id.radio_05);
        radio_06 = v.findViewById(R.id.radio_06);
        radio_07 = v.findViewById(R.id.radio_07);
        radio_08 = v.findViewById(R.id.radio_08);
        radio_09 = v.findViewById(R.id.radio_09);
        radio_10 = v.findViewById(R.id.radio_10);
        radio_11 = v.findViewById(R.id.radio_11);
        radio_12 = v.findViewById(R.id.radio_12);
        radio_13 = v.findViewById(R.id.radio_13);
        radio_14 = v.findViewById(R.id.radio_14);
        radio_15 = v.findViewById(R.id.radio_15);
        radio_16 = v.findViewById(R.id.radio_16);
        radio_17 = v.findViewById(R.id.radio_17);
        radio_18 = v.findViewById(R.id.radio_18);
        radio_19 = v.findViewById(R.id.radio_19);
        radio_20 = v.findViewById(R.id.radio_20);
        radio_21 = v.findViewById(R.id.radio_21);
        radio_22 = v.findViewById(R.id.radio_22);
        radio_23 = v.findViewById(R.id.radio_23);

        date_picker = v.findViewById(R.id.date_picker);
        picker_text = v.findViewById(R.id.picker_text);
        tv_act_service_picture = v.findViewById(R.id.tv_act_service_picture);
        tv_act_service_address1 = v.findViewById(R.id.tv_act_service_address1);
        tv_act_service_address2 = v.findViewById(R.id.tv_act_service_address2);
        tv_act_service_ceo = v.findViewById(R.id.tv_act_service_ceo);
        tv_act_service_name = v.findViewById(R.id.tv_act_service_name);
        tv_act_service_office = v.findViewById(R.id.tv_act_service_office);

        /**신청자 정보*/
        sv_register_nameTV = v.findViewById(R.id.sv_register_nameTV);
        sv_register_telTV = v.findViewById(R.id.sv_register_telTV);


        /** 사진*/
        workImage = v.findViewById(R.id.workImage);
        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity())) / 2;
        Adapter = new PlanImageRecyclerAdapter(getActivity(), itemHeight);
        workImage.setAdapter(Adapter);
        imageUriArray = new ArrayList<>();

        progress = v.findViewById(R.id.progress);
        service_register_btn = v.findViewById(R.id.service_register_btn);

        init_Transfer();
        init_Handler();
        init_Listener();
        Get_Company();
        Get_Engineer();

        return v;
    }

    /**
     * 이미지 정보
     */
    public void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        new ApiClient(data, "proc_worker_view", hdr);
    }

    /**
     * 상단 컴퍼니 정보
     */
    public void Get_Company() {
        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);
    }

    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() {

        tv_act_service_name.setText(fa.enterpriseItem.getArrayitem().getPtName());
        tv_act_service_office.setText(fa.enterpriseItem.getArrayitem().getCpName());
        tv_act_service_address1.setText(fa.enterpriseItem.getArrayitem().getCpAddr());
        tv_act_service_address2.setText(Common.getInstance().isNull(fa.enterpriseItem.getArrayitem().getCpAddrSub()).toString());
        tv_act_service_ceo.setText(Common.getInstance().isNull(fa.enterpriseItem.getArrayitem().getPtCeo()).toString());

        //서비스 신청자 > 명함관리쪽에서 데이터 가져오기
        if (fa.enterpriseItem.getArrayitem().getPtCeo() != null) {

            sv_register_nameTV.setText(fa.enterpriseItem.getArrayitem().getPtCeo());
        }

        if (fa.enterpriseItem.getArrayitem().getCpTel() != null) {

            sv_register_telTV.setText(fa.enterpriseItem.getArrayitem().getCpTel());
        }

        Date currentTime = Calendar.getInstance().getTime();
        String today = new SimpleDateFormat("yyyy년 MM월 dd일", Locale.getDefault()).format(currentTime);
        picker_text.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 = {radio_01, radio_02, radio_03, radio_04, radio_05, radio_06, radio_07, radio_08, radio_09,
                radio_10, radio_11, radio_12, radio_13, radio_14, radio_15, radio_16, radio_17, radio_18, radio_19, radio_20
                , radio_21, radio_22, radio_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());

        time_SV.scrollTo((set_time * width) + (margin * (set_time)), 0);


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

                service_register_btn.setEnabled(false);

                //상세증상
                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() + ")";
                    }
                }

                //방문시간
                String visit_time = "";
                RadioButton[] visitTimeRbtn = {radio_01, radio_02, radio_03, radio_04, radio_05, radio_06, radio_07, radio_08, radio_09,
                        radio_10, radio_11, radio_12, radio_13, radio_14, radio_15, radio_16, radio_17, radio_18, radio_19, radio_20
                        , radio_21, radio_22, radio_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();
                    }
                }

                if (engineer_name == null) {

                    Toast.makeText(getContext(), "방문기사를 선택하세요.", Toast.LENGTH_SHORT).show();
                    return;
                } else if (visit_time == null) {

                    Toast.makeText(getContext(), "방문시간을 선택하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }

                visit_time = visit_time + ":00";
                String visit_date = "";
                visit_date = picker_text.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;

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

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

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

                if (arr.isEmpty()) {

                    new ApiClient(data, "proc_service_registration", hdr);
                    Log.d("데이터 확인@@@", data.toString());
                } else {

                    new ApiClient(data, "proc_service_registration", uriData, hdr);
                    Log.d("데이터 확인@@@", data.toString());
                }
            }
        });


        /** 사진 촬영 */

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

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

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

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

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

        progress.setVisibility(View.GONE);
    }

    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_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()) {
                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), fa.enterpriseItem.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    } else 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());

                        Log.e("planDataArrayItem====", data.toString());


                        if (planDataArrayItem.isSuccess()) {
                            data = planDataArrayItem.getArrayitem().get(0);
                            Log.e("data====", data.toString());

                            Set_Contents();
                        } else {
                            Toast.makeText(getContext(), planDataArrayItem.getMessage(), Toast.LENGTH_SHORT).show();
                            getActivity().finish();
                        }
                    } else 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()) {

                            Toast.makeText(getContext(), engineer_array.getMessage(), Toast.LENGTH_SHORT).show();

                            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_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(), "서비스 접수가 완료되었습니다.", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getContext(), MainActivity.class);
                            startActivity(intent);

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

                } 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 url = msg.getData().getString("url");
                if (url.equals("proc_service_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");
                        Toast.makeText(getContext(), "저장되었습니다.", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();
                        getActivity().setResult(Activity.RESULT_OK, intent);
                    } else {
                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                    }
                    progress.setVisibility(View.GONE);
                } else if (url.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()) {
                        item = new ArrayList<>();
                        for (int i = 0; i < workImgDataArrayItem.getArrayitem().size(); i++) {
                            imageitems.add(workImgDataArrayItem.getArrayitem().get(i).getUrl());
                            new Service_Register_Fragment.ImageDownload(workImgDataArrayItem.getArrayitem().get(i).getPfiFilename().split("\\.")[0])
                                    .execute(workImgDataArrayItem.getArrayitem().get(i).getUrl());
                        }
                        Adapter.addItem(imageitems);
                        //PlanImageadapter.itemClick = itemClickListener2;
                    }
                }
                //Get_Contents();
            }
        };
    }


    @Override
    public void onStop() {
        super.onStop();
//        SharedPreferences pref = this.getActivity().getSharedPreferences("pref", Activity.MODE_PRIVATE);
//        SharedPreferences.Editor editor = pref.edit();
//
//        /** 체크된 상세증상 저장 */
//        editor.putBoolean("check_01", check_01.isChecked());
//        editor.putBoolean("check_02", check_02.isChecked());
//        editor.putBoolean("check_03", check_03.isChecked());
//        editor.putBoolean("check_04", check_04.isChecked());
//        editor.putBoolean("check_05", check_05.isChecked());
//        editor.putBoolean("check_06", check_06.isChecked());
//        editor.putBoolean("check_07", check_07.isChecked());
//        editor.putBoolean("check_08", check_08.isChecked());
//        editor.putBoolean("check_09", check_09.isChecked());
//        editor.putBoolean("check_10", check_10.isChecked());
//        editor.putBoolean("check_11", check_11.isChecked());
//        editor.putBoolean("check_12", check_12.isChecked());
//
//        /** 체크된 방문시간 저장 */
//        editor.putBoolean("radio_01", radio_01.isChecked());
//        editor.putBoolean("radio_02", radio_02.isChecked());
//        editor.putBoolean("radio_03", radio_03.isChecked());
//        editor.putBoolean("radio_04", radio_04.isChecked());
//        editor.putBoolean("radio_05", radio_05.isChecked());
//        editor.putBoolean("radio_06", radio_06.isChecked());
//        editor.putBoolean("radio_07", radio_07.isChecked());
//        editor.putBoolean("radio_08", radio_08.isChecked());
//        editor.putBoolean("radio_09", radio_09.isChecked());
//
//
//        /** 방문기사 저장 */
//
//        editor.putBoolean("radio_back", back_dri.isChecked());
//        editor.putBoolean("radio_park", park_dri.isChecked());
//        editor.putBoolean("radio_kim", kim_dri.isChecked());
//        editor.putBoolean("radio_choi", choi_dri.isChecked());
//
//
//        editor.commit();

    }

    private void init_Listener() {

        date_picker.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;
                picker_text.setText(year + "년 " + month + "월 " + dayOfMonth + "일");

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

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
    }


    private class ImageDownload extends AsyncTask<String, Void, 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 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();
            }
        }
    }
}