package com.example.smart119.views

import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.GridView
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.smart119.API_Helper
import com.example.smart119.AlertDialogUtil
import com.example.smart119.ListItem
import com.example.smart119.LocationHelper
import com.example.smart119.LoginManager
import com.example.smart119.MedicalInfo
import com.example.smart119.MyCookieJar
import com.example.smart119.R
import com.example.smart119.SpreadsheetAdapter
import com.example.smart119.ViewPagerAdapter
import com.example.smart119.databinding.FragmentSecondBinding
import com.example.smart119.datas.HospitalSearch
import com.example.smart119.interfaces.RetrofitClient
import com.example.smart119.views.PaginationHelper.pageRequest
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.JsonObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

import java.text.SimpleDateFormat
import java.util.Date
import kotlin.math.log

/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class HospitalSearchFragment : Fragment() {

    private var _binding: FragmentSecondBinding? = null
    private var _listAdapterInit: Boolean? = false
    private lateinit var adapter: SpreadsheetAdapter
//    private val

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentSecondBinding.inflate(inflater, container, false)
        return binding.root
    }

    //창이 보여질때 실행되는 함수
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        FragmentHandler.registerView("HospitalSearchFragment", view)

        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // 뒤로 가기 동작 막음
//                println("Hospital 뒤로가기클릭!!")
            }
        })


        //#region 탭 레이아웃 설정
        val tabLayout: TabLayout = view.findViewById(R.id.tabLayout)
        val viewPager: ViewPager2 = view.findViewById(R.id.viewPager)

        // ViewPager 어댑터 설정
        val vpAdapter = ViewPagerAdapter(requireActivity())
        viewPager.adapter = vpAdapter

        // TabLayout과 ViewPager 연결
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = when (position) {
                0 -> "주소 기반 검색"
                1 -> "위치 기반 검색"
                else -> "주소 기반 검색"
            }
        }.attach()
        //#endregion

        //hospitalInit(view);
//        HospitalSearch.clearAllData()

        if (HospitalSearch.get_gps_address().isEmpty()) {
            println("hospital search address updated!")
//            Hospital_UIUpdate()
        }
        else {
//            Hospital_UIUpdate_SET()
        }


        /*
        //병원검색 버튼 이벤트
        binding.hospSearchButton.setOnClickListener {

            var _sel_medical = view.findViewById<Spinner>(R.id.spMedical).selectedItem as String;
            var _sel_depart = view.findViewById<Spinner>(R.id.spDepart).selectedItem as String;
            var _sel_emg_yn = view.findViewById<Spinner>(R.id.spEmgYN).selectedItem as String;

            adapter.clearHospitalList();
            HospitalSearch.clearAllData();

            if (HospitalSearch.getIsFiltered()) {
                var searchObject = HospitalSearch.getSearchInfo()
                var filter_si = searchObject["si"].asString;
                var filter_gu = searchObject["gu"].asString;
                var filter_relate = searchObject["relate"].asString;

                var reqBody: JsonObject = API_Helper.make_addressHosp_param(
                    filter_si, filter_gu, "", filter_relate
                );
                try {
                    LoadingDialog.showDlg(requireContext())
                    HospitalSearch.SET_SearchRequest(true, reqBody)
                    RetrofitClient.locInstance.getAddressHospitalList(reqBody).enqueue(getAddressResponse())
                } catch (e: Exception) {
                    println(e.message)
                } finally {
                    LoadingDialog.hideDlg()
                }
            } else {
                LocationHelper.getLastKnownLocation({ res ->
                    //success
                    val resObj = res.getAsJsonObject();
                    val callResult = resObj["isSuccess"]?.asBoolean ?: true;
                    val lon = resObj["lon"]?.asDouble ?: 0.0;
                    val lat = resObj["lat"]?.asDouble ?: 0.0;

                    var page = "1"
                    var row = "4"
                    var dg_list = emptyList<String>()//listOf("","")

                    var _code_medical = MedicalInfo.get_emogemdv_code(_sel_medical);
                    var _code_depart = MedicalInfo.get_prt_code(_sel_depart);
                    var _emg_yn = _sel_emg_yn;
                    var _relate = ""

                    try {
                        _relate = HospitalSearch.getSearchInfo()["relate"].asString;
                    } catch (e: Exception) {
                        println(e.message)
                    }

                    if (_code_medical == null) _code_medical = ""
                    if (_code_depart == null) _code_depart = ""
                    if (_emg_yn == "응급실 포함여부 선택") _emg_yn = "Y"

//                    println("의료기관:${_sel_medical}|${_code_medical}, 진료과:${_sel_depart}|${_code_depart}, 응급실:${_emg_yn}")

                    var reqBody :JsonObject = API_Helper.make_arroundHosp_param2(
                        lon = lon.toString(),
                        lat = lat.toString(),
                        emogemdv = "${_code_medical}",
                        prtcode = "${_code_depart}",
                        emergency = "${_emg_yn}",
                        emogdesc = "${_relate}",
                        page = "${page}",
                        row = "${row}"
                    );

                    try {
                        LoadingDialog.showDlg(requireContext())
                        HospitalSearch.SET_SearchRequest(false, reqBody)
                        RetrofitClient.locInstance.getAroundHospitalList(reqBody).enqueue(arroundHospitalResponse())
                    } catch (e: Exception) {
                        println(e.message)
                    } finally {
                        LoadingDialog.hideDlg()
                    }
                }, { res ->
                    //fail
                    val resObj = res.getAsJsonObject();
                    val callResult = resObj["isSuccess"]?.asBoolean ?: false;
                    val lon = resObj["lon"]?.asDouble ?: 0.0;
                    val lat = resObj["lat"]?.asDouble ?: 0.0;
                    println("[FAIL] last location ${lon}, ${lat}");

                    AlertDialogUtil.showAlert(
                        context = requireActivity(),
                        title = "병원 검색 결과",
                        message = "현재 위치를 알수 없어 검색 되지 않았습니다, 다시 시도해주세요."
                    )
                })
            }

        }
//        binding.searchAddressButton.setOnClickListener {
//            val inflater = LayoutInflater.from(requireActivity())
//            val popupView = inflater.inflate(R.layout.popup_search, null)
//
//            var itemSido = HospitalSearch.getSidoList();
//            var itemSidoAlpha:MutableList<String> = itemSido.toMutableList()
//            itemSidoAlpha.add(0, "시도선택")
//
//            var newPopup = HospitalSearchPopup.showPopupHospitalSearch(popupView, requireActivity())
//            HospitalSearchPopup.set_POPUP_SIDO_COMBO(newPopup, requireActivity(), itemSidoAlpha)
//
//            HospitalSearch.set_popup_search(newPopup)
//        }
//        binding.cbActiveAddresss.setOnCheckedChangeListener { _, isChecked ->
//            if (isChecked) {
//                HospitalSearch.setFiltered(true)
//            } else {
//                HospitalSearch.setFiltered(false)
//            }
//        }
        binding.pagePrev.setOnClickListener {
            if (HospitalSearch.getAllData().size > 0) {
                var bChanged = PaginationHelper.prevPage(requireView(), { page ->
                    page_onclick_listener(page)
                })
                //request page
                if (bChanged) {
                    var currPage = PaginationHelper.currentPage;
//                    println("prev request number ${PaginationHelper.currentPage}")
                    page_onclick_listener(currPage)
                }
//                else println("no request prev")
            }
        }
        binding.pageNext.setOnClickListener {
            if (HospitalSearch.getAllData().size > 0) {
                var bChanged = PaginationHelper.nextPage(requireView(), { page ->
                    page_onclick_listener(page)
                })
                //request page
                if (bChanged) {
                    var currPage = PaginationHelper.currentPage;
//                    println("next request number ${PaginationHelper.currentPage}")
                    page_onclick_listener(currPage)
                }
//                else println("no request next")
            }
        }
        binding.gpsRefresh.setOnClickListener {
            Hospital_UIUpdate()
        }
        */

        //HospitalSearch.init_hospital_req(requireActivity())
    }

    private fun arroundHospitalResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                if (response.isSuccessful) {
                    var resBody = response.body();
                    set_hospital_list(resBody)
                } else {
                    Toast.makeText(
                        requireActivity(),
                        "Error: ${response.code()}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                Toast.makeText(
                    requireActivity(),
                    "Request Failed: ${t.message}",
                    Toast.LENGTH_SHORT
                ).show()

                /*

                var hospitalSearchRes: List<List<String>> = mutableListOf()
                var hpidList: MutableList<String> = mutableListOf()
                HospitalSearch.addDataHospitalItems(
                    listOf(
                        HospitalSearch.itemStructure(
                            "A1100223", API_Helper.lidar_levelState(3), "1.11",
                            "서울특별시", "양천구", "1566-6688", "서울특별시서남병원"
                        ),// 126.8371889, 37.5124604
                        HospitalSearch.itemStructure(
                            "A1100055", API_Helper.lidar_levelState(-1), "2.22",
                            "서울특별시", "영등포구", "02-829-5114", "한림대학교 강남성심병원"
                        ),
                        HospitalSearch.itemStructure(
                            "A1100004", API_Helper.lidar_levelState(-1), "3.33",
                            "서울특별시", "용산구", "02-709-9114", "순천향대학교 부속 서울병원"
                        )
                        //용산 주변 좌표
                        //lon 126.9984597, lat 37.5287920
                    )
                )
                hospitalSearchRes = HospitalSearch.getAllData();

                hpidList.add("A1100223")
                hpidList.add("A1100055")
                hpidList.add("A1100004")

                if (hospitalSearchRes.size > 0)
                    adapter.hospitalListUpdate(hospitalSearchRes, hpidList)

                */
            }
        }
    }

    private fun hospitalInit(view: View) {

        /*
        var items = listOf(
            ListItem.Header(listOf("병원이름")), // 헤더 열 정의
            ListItem.Header(listOf("주소")),
            ListItem.Header(listOf("전화번호")),
            ListItem.Header(listOf("라이다 혼잡도")),
            ListItem.Header(listOf("거리")),
            ListItem.Header(listOf("병원별 이송 시작"))
        )
        val recyclerView: RecyclerView = view.findViewById(R.id.reCyclerView)

        val spanCount = 6;
        adapter = SpreadsheetAdapter(
            items,
            onButtonClick = { row, pos ->
                //row.values[0]

                adapter.setSelectedHospitalPos(pos)
                HospitalSearch.setIdx(adapter.getSelectedPosition())
                var selectedHospital = adapter.getSelectedHospital()
                var getSelData = HospitalSearch.getSelectedData()
                if (selectedHospital is ListItem.Row) {
                    var hospitalName = selectedHospital.values[0];
                    var hospitalAddress = selectedHospital.values[1];
                    var hospitalCallNumber = selectedHospital.values[2];
                    var hospitalLiDAR = selectedHospital.values[3];
                    var hospitalDistance = selectedHospital.values[4];
                    if (TransferManager.getState() == TransferState.STARTED) {
                        //이송 변경
                        //변경된 병원 정보 설정
                        AlertDialogUtil.showAlert(
                            context = requireActivity(),
                            title = "변경 이송 병원 정보",
                            message = "병원 이름 : ${hospitalName}" + "\n" +
                                    "주소 : ${hospitalAddress}" + "\n" +
                                    "전화번호 : ${hospitalCallNumber}" + "\n" +
                                    "거리 : ${hospitalDistance}" + "\n" +
                                    "라이다혼잡도 : ${hospitalLiDAR}" + "\n\n" +
                                    "확인 선택시 진행(변경 시 기존 이송 정보가 변경됩니다.)",
                            onPositiveClick = {
                                val bottomNaviView =
                                    requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navigation)
                                bottomNaviView.selectedItemId = R.id.hospTransfer;
                                TransferManager.changeTransfer()
                            },
                            onNegativeClick = {}
                        )

                    } else {
                        AlertDialogUtil.showAlert(
                            context = requireActivity(),
                            title = "이송 병원 정보",
                            message = "병원 이름 : ${hospitalName}" + "\n" +
                                    "주소 : ${hospitalAddress}" + "\n" +
                                    "전화번호 : ${hospitalCallNumber}" + "\n" +
                                    "라이다혼잡도 : ${hospitalLiDAR}" + "\n\n" +
                                    "확인 선택시 진행",
                            onPositiveClick = {
                                if (TransferManager.startTransfer()) {
                                    val bottomNaviView =
                                        requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navigation)
                                    bottomNaviView.selectedItemId = R.id.hospTransfer;
                                } else {
                                    // 시작되지 않았습니다.
                                    Toast.makeText(
                                        requireActivity(), "이송이 시작되지 않았습니다. 다시 전송해주세요.",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                            },
                            onNegativeClick = {}
                        )
                    }
                } else {
                    AlertDialogUtil.showAlert(
                        context = requireActivity(),
                        title = "선택된 병원 정보",
                        message = "병원 검색 후 선택해주세요!"
                    )
                }
                //이송시작
                println(row)

                //pos, row(ListItem상 선택 위치, 선택한 row 정보) -> hpid는?
            },
            onRowClick = { row ->
//                Toast.makeText(requireActivity(), "${row.values[0]}이 선택되었습니다.", Toast.LENGTH_SHORT)
//                    .show()
            }
        )
        adapter.setColumnCount(spanCount)
        recyclerView.adapter = adapter

        // GridLayoutManager 설정
        val layoutManager = GridLayoutManager(requireActivity(), spanCount)
        layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
//                return if (adapter.getItemViewType(position) == SpreadsheetAdapter.VIEW_TYPE_HEADER) 3 else 1
                return if (adapter.getItemViewType(position) == SpreadsheetAdapter.VIEW_TYPE_ROW) {
                    spanCount // Row가 전체 열을 차지하도록 설정
                } else {
                    1 // 기본적으로 각 항목은 한 열을 차지
                }
            }
        }
        recyclerView.layoutManager = layoutManager
        */
    }

    private fun Hospital_UIUpdate_SET() {
        var hsfView = FragmentHandler.getView("HospitalSearchFragment")
        if (hsfView != null) {
            var addrString = HospitalSearch.get_gps_address()
            var geoTv = hsfView.findViewById<TextView>(R.id.tvGeoLocation)
            geoTv.text = addrString;
        }
    }

    private fun Hospital_UIUpdate() {

    }

    //길찾기 API 결과
    private fun getPathAddressResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                if (response.isSuccessful) {
                    val resObj = response.body();
                    val metaObj = resObj?.get("meta");
                    if (metaObj != null) {
                        val tot_count = metaObj.asJsonObject["total_count"].asInt
                        if (tot_count > 0) {
                            var hsfView = FragmentHandler.getView("HospitalSearchFragment")
                            if (hsfView != null) {

                                val docus = resObj.getAsJsonArray("documents")
                                val addObj = docus[0].asJsonObject["address"];
                                val add_full = addObj.asJsonObject["address_name"]
                                val add_si = addObj.asJsonObject["region_1depth_name"]
                                val add_gu = addObj.asJsonObject["region_2depth_name"]
                                val add_dong = addObj.asJsonObject["region_3depth_name"]

                                var geoTv = hsfView.findViewById<TextView>(R.id.tvGeoLocation)
                                geoTv.text = add_full.asString;

                                HospitalSearch.set_gps_update(add_full.asString)
                            }
                        }
                    }
                    //response.body()["meta"].asJsonObject["total_count"]
                    println(response)
                } else {
                    println("address not found")
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                println(t.message)
            }
        }
    }

    private fun getAddressResponse(): Callback<JsonObject>{
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                if (response.isSuccessful) {
                    val resObj = response.body();
                    set_hospital_list(resObj, true)
                } else {
                    println("hospital not found")
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                println(t.message)
            }
        }
    }

    fun set_hospital_list(resobj:JsonObject?, isAddress:Boolean = false) {
        var totPages = resobj?.get("totalPages") // 총 페이지
        var totRows = resobj?.get("totalRows") // 총 행 개수
        var searchRows = resobj?.get("row") // 검색 페이지 행 개수
        var searchPage = resobj?.get("page") // 검색 페이지 번호
        var resData = resobj?.getAsJsonArray("resData")
        var dataSize = resData?.size() ?: 0;

        var hospitalSearchRes: List<List<String>> = mutableListOf()
        var hpidList: MutableList<String> = mutableListOf()
        if (dataSize > 0) {
            // region 검색 결과 리스트에 세팅
            try {
                resData?.forEach { item ->
                    val itemObj = item.asJsonObject;
                    var levelState =
                        API_Helper.lidar_levelState(itemObj.get("levelState").asInt)
                    var itemHpid = itemObj.get("hpid").toString().trim('"');
                    hpidList.add(itemHpid)
                    var itemDistance = ""
                    var itemTel = ""
                    var itemTitle = ""
                    if (!isAddress) {
                        itemObj.get("distance").toString().trim('"')
                        itemTel = itemObj.get("tel").toString().trim('"')
                        itemTitle = itemObj.get("title").toString().trim('"')
                    }
                    else {
                        itemTel = itemObj.get("dutyTel1").toString().trim('"')
                        itemTitle = itemObj.get("dutyName").toString().trim('"')
                    }

                    HospitalSearch.addDataHospitalItems(
                        listOf(
                            HospitalSearch.itemStructure(
                                itemHpid, levelState, itemDistance,
                                itemObj.get("city").toString().trim('"'),
                                itemObj.get("district").toString().trim('"'),
                                itemTel, itemTitle
                            )
                        )
                    )
                }

                var total_Page = totPages?.asInt;
                if (total_Page == null) total_Page = 0;
                var total_Row = totRows?.asInt;
                if (total_Row == null) total_Row = 0;
                PaginationHelper.setupPaginationLayout(requireView(), total_Page, total_Row, { page ->
                    page_onclick_listener(page)
                })

            } catch (e: Exception) {
                Toast.makeText(requireActivity(), "${e.message}", Toast.LENGTH_LONG)
                    .show()
            } finally {}

            hospitalSearchRes = HospitalSearch.getAllData();
        } else {
            AlertDialogUtil.showAlert(
                context = requireActivity(),
                title = "병원 검색 결과",
                message = "병원이 검색되지 않았습니다. 다시 시도해주세요."
            )

            if (!PaginationHelper.pageRequest) PaginationHelper.setupPaginationLayout(
                requireView(),
                0, 0, { page ->
                    page_onclick_listener(page)
                }
            )
        }

        //병원 검색 결과 설정
        if (hospitalSearchRes.size > 0) adapter.hospitalListUpdate(hospitalSearchRes, hpidList)
        // endregion
    }

    private fun page_onclick_listener(page:Int) {
//        println("clicked page ${page}")
        var reqBody = HospitalSearch.GET_SearchRequest()
        if (reqBody != null) {
            try {
                if (HospitalSearch.isAddressSearch()) {
                    LoadingDialog.showDlg(requireContext())
                    reqBody = reqBody.getAsJsonObject("reqBody")
                    reqBody.addProperty("page", "${page}")
                    RetrofitClient.locInstance.getAddressHospitalList(reqBody).enqueue(getAddress_Paging_Response())
                } else {
                    LoadingDialog.showDlg(requireContext())
                    reqBody = reqBody.getAsJsonObject("reqBody")
                    reqBody.addProperty("page", "${page}")
                    RetrofitClient.locInstance.getAroundHospitalList(reqBody).enqueue(arroundHospital_Paging_Response())
                }
            } catch (e: Exception) {
                println(e.message)
            } finally {
                LoadingDialog.hideDlg()
            }
        }
    }

    private fun arroundHospital_Paging_Response(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                LoadingDialog.hideDlg()
                if (response.isSuccessful) {
                    var resBody = response.body();
                    set_hospital_list_page(resBody)
                } else {
                    Toast.makeText(
                        requireActivity(),
                        "Error: ${response.code()}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                LoadingDialog.hideDlg()
                Toast.makeText(
                    requireActivity(),
                    "Request Failed: ${t.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun getAddress_Paging_Response(): Callback<JsonObject>{
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                LoadingDialog.hideDlg()
                if (response.isSuccessful) {
                    val resObj = response.body();
                    set_hospital_list_page(resObj, true)
                } else {
                    println("hospital not found")
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                LoadingDialog.hideDlg()
                println(t.message)
            }
        }
    }

    fun set_hospital_list_page(resobj:JsonObject?, isAddress:Boolean = false) {
        // region 현재 병원 리스트 초기화
        adapter.clearHospitalList();
        HospitalSearch.clearAllData();
        // endregion

        var totPages = resobj?.get("totalPages") // 총 페이지
        var totRows = resobj?.get("totalRows") // 총 행 개수
        var searchRows = resobj?.get("row") // 검색 페이지 행 개수
        var searchPage = resobj?.get("page") // 검색 페이지 번호
        var resData = resobj?.getAsJsonArray("resData")
        var dataSize = resData?.size() ?: 0;

        var hospitalSearchRes: List<List<String>> = mutableListOf()
        var hpidList: MutableList<String> = mutableListOf()
        if (dataSize > 0) {
            // region 검색 결과 리스트에 세팅
            try {
                resData?.forEach { item ->
                    val itemObj = item.asJsonObject;
                    var levelState =
                        API_Helper.lidar_levelState(itemObj.get("levelState").asInt)
                    var itemHpid = itemObj.get("hpid").toString().trim('"');
                    hpidList.add(itemHpid)
                    var itemDistance = ""
                    var itemTel = ""
                    var itemTitle = ""
                    if (!isAddress) {
                        itemObj.get("distance").toString().trim('"')
                        itemTel = itemObj.get("tel").toString().trim('"')
                        itemTitle = itemObj.get("title").toString().trim('"')
                    }
                    else {
                        itemTel = itemObj.get("dutyTel1").toString().trim('"')
                        itemTitle = itemObj.get("dutyName").toString().trim('"')
                    }

                    HospitalSearch.addDataHospitalItems(
                        listOf(
                            HospitalSearch.itemStructure(
                                itemHpid, levelState, itemDistance,
                                itemObj.get("city").toString().trim('"'),
                                itemObj.get("district").toString().trim('"'),
                                itemTel, itemTitle
                            )
                        )
                    )
                }

                var total_Page = totPages?.asInt;
                if (total_Page == null) total_Page = 0;
                var total_Row = totRows?.asInt;
                if (total_Row == null) total_Row = 0;

//                PaginationHelper.rePaginationLayout(requireView(), { page ->
//                    page_onclick_listener(page)
//                })
//                PaginationHelper.setupPaginationLayout(requireView(), total_Page, total_Row, { page ->
//                    page_onclick_listener(page)
//                })

            } catch (e: Exception) {
                Toast.makeText(requireActivity(), "${e.message}", Toast.LENGTH_LONG)
                    .show()
            } finally {}

            hospitalSearchRes = HospitalSearch.getAllData();
        } else {
            AlertDialogUtil.showAlert(
                context = requireActivity(),
                title = "병원 검색 결과",
                message = "병원이 검색되지 않았습니다. 다시 시도해주세요."
            )

//            if (!PaginationHelper.pageRequest) PaginationHelper.setupPaginationLayout(
//                requireView(),
//                0, 0, { page ->
//                    page_onclick_listener(page)
//                }
//            )
        }

        //병원 검색 결과 설정
        if (hospitalSearchRes.size > 0) adapter.hospitalListUpdate(hospitalSearchRes, hpidList)
        // endregion
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        FragmentHandler.unregisterView("HospitalSearchFragment")
        println("hospital search On destroy view")
    }

}
