package com.example.smart119.views

import android.graphics.Typeface
import android.location.Location
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.smart119.API_Helper
import com.example.smart119.AlertDialogUtil
import com.example.smart119.HelpUtility
import com.example.smart119.ListItem
import com.example.smart119.LocationHelper
import com.example.smart119.LoginManager
import com.example.smart119.MedicalInfo
import com.example.smart119.R
import com.example.smart119.SpreadsheetAdapter
import com.example.smart119.TransferManager
import com.example.smart119.TransferState
import com.example.smart119.datas.HospitalSearch
import com.example.smart119.datas.SaveLogin
import com.example.smart119.interfaces.RetrofitClient
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.JsonObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LocationSearchFragment : Fragment() {
    private lateinit var lsAdapter: SpreadsheetAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.location_search_page, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        FragmentHandler.registerView("LocationSearchFragment", view)

        hospitalInit(view);
        HospitalSearch.clearAllData()

        val searchButton = view.findViewById<Button>(R.id.hospSearchButton)
        searchButton.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;

            lsAdapter.clearHospitalList();
            HospitalSearch.clearAllData();

            //success
//            val resObj = res.getAsJsonObject();
//            val callResult = resObj["isSuccess"]?.asBoolean ?: true;
            val lon = LocationHelper.getCurrentLon();
            val lat = LocationHelper.getCurrentLat();

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

            val hospCatTV = view.findViewById<TextView>(R.id.hospCatLocText)
            val hospPrtTV = view.findViewById<TextView>(R.id.hospPrtLocText)

            var _code_medical = MedicalInfo.get_emogemdv_code(hospCatTV.text.toString());
            var _code_depart = MedicalInfo.get_prt_code(hospPrtTV.text.toString());
            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.indexOf("응급실 포함여부") != -1) _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)
                LoadingDialog.hideDlg()
            }

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

        }

        val prevLSButton = view.findViewById<Button>(R.id.pagePrevLS)
        prevLSButton.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")
            }
        }

        val nextLSButton = view.findViewById<Button>(R.id.pageNextLS)
        nextLSButton.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")
            }
        }

        val gpsRefreshButton = view.findViewById<ImageButton>(R.id.gpsRefresh)
        gpsRefreshButton.setOnClickListener {
            Hospital_UIUpdate(true)
        }

        val hospCatLocTV = view.findViewById<TextView>(R.id.hospCatLocText)
        hospCatLocTV.setOnClickListener {
            HospitalCategoryLocation_Dialog.show(requireContext())
        }

        HospitalCategoryLocation_Dialog.registerCallback { evtString ->
            println("의료기관 선택 이벤트!! ${evtString}")
        }

        val hospPrtLocTV = view.findViewById<TextView>(R.id.hospPrtLocText)
        hospPrtLocTV.setOnClickListener {
            DepartmentLocation_Dialog.show(requireContext())
        }

        DepartmentLocation_Dialog.registerCallback { evtString ->
            println("진료과 선택 이벤트!! ${evtString}")
        }

        try {
            if (!HospitalSearch.get_gps_address().isEmpty()) {
                Hospital_UIUpdate_SET(view)
            }
            Hospital_UIUpdate()
        } catch (e: Exception) {
            println(e.message)
        }
    }

    override fun onResume() {
        super.onResume()
//        Toast.makeText(requireContext(), "위치기반 탭 활성화!", Toast.LENGTH_SHORT).show()
//        println("위치기반 탭 활성화!")
    }

    override fun onPause() {
        super.onPause()
//        println("위치기반 탭 비 활성화!")
        lsAdapter.clearHospitalList()
        HospitalSearch.clearAllData()
        PaginationHelper.setupPaginationLayout(
            requireView(),
            0, 0, { page ->
                page_onclick_listener(page)
            }
        )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        FragmentHandler.unregisterView("LocationSearchFragment")
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    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 recyclerViewLS: RecyclerView = view.findViewById(R.id.reCyclerViewLS)

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

                lsAdapter.setSelectedHospitalPos(pos)
                HospitalSearch.setIdx(lsAdapter.getSelectedPosition())
                var selectedHospital = lsAdapter.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) {
                        //이송 변경
                        //변경된 병원 정보 설정
                        val spannableMessage = SpannableStringBuilder().apply {
                            val preText = "병원 이름 : ${hospitalName}" + "\n" +
                                    "주소 : ${hospitalAddress}" + "\n" +
                                    "전화번호 : ${hospitalCallNumber}" + "\n" +
                                    "거리 : ${hospitalDistance}" + "\n" +
                                    "라이다혼잡도 : ${hospitalLiDAR}" + "\n"
                            append(preText)

                            val boldText = "확인"
                            append(boldText)
                            setSpan(
                                StyleSpan(Typeface.BOLD), preText.length,
                                preText.length + boldText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                            )
                            append(" 선택시 환자정보가 전송됩니다.(변경 시 기존 이송 병원이 변경됩니다.)\n")
                        }

                        AlertDialogUtil.showAlert_CUSTOM(
                            context = requireActivity(),
                            title = "이송 병원 정보",
                            sppStr = spannableMessage,
                            onPositiveClick = {
                                AlertDialogUtil.showAlert_OK(
                                    context = requireActivity(),
                                    title = "진행 전 확인사항",
                                    message = "진행하시기 전에, 구급활동일지 임시저장을 하셨는지 확인해 주세요\n",
                                    onPositiveClick = {
                                        val bottomNaviView =
                                            requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navigation)
                                        bottomNaviView.selectedItemId = R.id.hospTransfer;
                                        TransferManager.changeTransfer()
                                    }
                                )
                            },
                            onNegativeClick = {}
                        )

                    } else {
                        val spannableMessage = SpannableStringBuilder().apply {
                            val preText = "병원 이름 : ${hospitalName}" + "\n" +
                                    "주소 : ${hospitalAddress}" + "\n" +
                                    "전화번호 : ${hospitalCallNumber}" + "\n" +
                                    "거리 : ${hospitalDistance}" + "\n" +
                                    "라이다혼잡도 : ${hospitalLiDAR}" + "\n"
                            append(preText)

                            val boldText = "확인"
                            append(boldText)
                            setSpan(
                                StyleSpan(Typeface.BOLD), preText.length,
                                preText.length + boldText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                            )
                            append(" 선택시 환자정보가 전송됩니다.\n")
                        }

                        AlertDialogUtil.showAlert_CUSTOM(
                            context = requireActivity(),
                            title = "이송 병원 정보",
                            sppStr = spannableMessage,
                            onPositiveClick = {

                                AlertDialogUtil.showAlert_OK(
                                    context = requireActivity(),
                                    title = "진행 전 확인사항",
                                    message = "진행하시기 전에, 구급활동일지 임시저장을 하셨는지 확인해 주세요\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()
            }
        )
        lsAdapter.setColumnCount(spanCount)
        recyclerViewLS.adapter = lsAdapter

        // 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 (lsAdapter.getItemViewType(position) == SpreadsheetAdapter.VIEW_TYPE_ROW) {
                    spanCount // Row가 전체 열을 차지하도록 설정
                } else {
                    1 // 기본적으로 각 항목은 한 열을 차지
                }
            }
        }
        recyclerViewLS.layoutManager = layoutManager
    }

    private fun Hospital_UIUpdate(bForceUpdate:Boolean = false) {
        val lon = LocationHelper.getCurrentLon();
        val lat = LocationHelper.getCurrentLat();
        val currentTime = System.currentTimeMillis()
        val _prev_gps = HospitalSearch.getPrevGPSInfo()
//            println("lon:${lon}, lat:${lat}, prev lon:${_prev_gps["prevLon"].asDouble}, prev lat:${_prev_gps["prevLat"].asDouble}")

        //이전 업데이트가 1km 이내에서 한 경우, 업데이트 하지 않음
        if (shouldUpdateLocation(
                _prev_gps["prevLat"].asDouble,
                _prev_gps["prevLon"].asDouble,
                _prev_gps["prevTime"].asLong,
                lat,
                lon,
                currentTime
            ) || bForceUpdate
        ) {
            RetrofitClient.pathInstance.getAddr(
                API_Helper.make_getAddr_param(lon.toString(), lat.toString())
            ).enqueue(getPathAddressResponse())
            HospitalSearch.setPrevGPSUpdate(lon, lat, System.currentTimeMillis())
            println("카카오 위치 -> 주소 변환 API 요청");
        } else {
            println("카카오 위치 -> 주소 변환 API 요청 안함");
        }
    }
    private fun Hospital_UIUpdate_SET(view:View) {
        var addrString = HospitalSearch.get_gps_address()
        var geoTv = view.findViewById<TextView>(R.id.tvGeoLocation)
        geoTv.text = addrString;
    }

    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) {
                            val lsfView = requireView()
                            if (lsfView != 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 = lsfView.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 arroundHospitalResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                LoadingDialog.hideDlg()
                if (response.isSuccessful) {
                    val resBody = response.body();
                    if (resBody != null) {
                        set_hospital_list(resBody)
                    }
                    else {
                        nav_to_login();
                    }
                } else {
                    nav_to_login();
                }
            }

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


    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) {
                        itemDistance = 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) lsAdapter.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)
                LoadingDialog.hideDlg()
            }
        }
    }

    /*
    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)
            }
        }
    }
    */
    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) {
                    val resBody = response.body();
                    if (resBody != null) {
                        set_hospital_list_page(resBody)
                    }
                    else {
                        nav_to_login();
                    }
                } else {
                    nav_to_login();
                }
            }

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

    fun set_hospital_list_page(resobj:JsonObject?) {
        // region 현재 병원 리스트 초기화
        lsAdapter.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) {
                    //위치기반 검색 시 사용하는 곳
                    itemDistance = 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) lsAdapter.hospitalListUpdate(hospitalSearchRes, hpidList)
        // endregion
    }

    fun shouldUpdateLocation(
        prevLat: Double, prevLng: Double, prevTime: Long, // 이전 위도, 경도, 업데이트 시간 (ms)
        newLat: Double, newLng: Double, newTime: Long, // 새로운 위도, 경도, 현재 시간 (ms)
        intervalMs: Long = 300000 // 기본 업데이트 주기: 5분 (300,000ms)
    ): Boolean {
        val prevLocation = Location("").apply {
            latitude = prevLat
            longitude = prevLng
        }

        val newLocation = Location("").apply {
            latitude = newLat
            longitude = newLng
        }

        val distance = prevLocation.distanceTo(newLocation) // 두 지점 간 거리 (단위: m)
        val timeDiff = newTime - prevTime // 시간 차이 (ms)

        println("${distance}, ${timeDiff}")
        val state_dist = (distance >= 1000)
        val state_time = (timeDiff >= intervalMs)
        val state_lonlat = (prevLat != newLat || prevLng != newLng)
        val state_lonlatDist = ((prevLat != newLat || prevLng != newLng) && distance >= 1000)
        println("${state_dist}, ${state_time}, ${state_lonlat}, ${state_lonlatDist}")

        return ((prevLat != newLat || prevLng != newLng) && distance >= 1000) || timeDiff >= intervalMs
    }

    fun nav_to_login() {
        AlertDialogUtil.showAlert_OK(
            context = requireActivity(),
            title = "세션 만료",
            message = "기존 세션이 만료되었습니다. 다시 로그인 해주시기 바랍니다.\n",
            onPositiveClick = {
                SaveLogin.setLogin(false)
                LoginManager.setLoggedIn(false);
                val bottomNaviView =
                    requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navigation)
                bottomNaviView.selectedItemId = R.id.emgLogin;
            }
        )
    }


}