package com.ydl.confide.home

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.tencent.smtt.sdk.WebSettings
import com.ydl.confide.R
import com.ydl.webview.ProgressWebView
import com.ydl.webview.TellData
import com.ydl.webview.WebModularServiceUtils
import com.ydl.ydlcommon.base.BaseActivity
import com.yidianling.common.tools.RxImageTool

class ConfideBottomSheetDialogFragment : BottomSheetDialogFragment() {
    companion object {
        private const val KEY_JUMP_URL = "jumpUrl"
    }
    lateinit var wv_content:ProgressWebView;
    lateinit var text_title:View;
    lateinit var line:View;
    lateinit var rl_title:View;
    lateinit var close_webview_Icon:View
    lateinit var jumpUrl:String
    fun showBottomSheetDialog(activity: FragmentActivity,jumpUrl:String) {
        arguments = Bundle().apply {
            putString(KEY_JUMP_URL, jumpUrl)
        }
        show(activity.supportFragmentManager, "confide_bottom_showdialog")
    }

    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL,R.style.AppBottomSheet)

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.confide_webview, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        jumpUrl = arguments?.getString(KEY_JUMP_URL) ?: ""
        if (jumpUrl.isBlank()) {
            dismiss()
            return
        }
        wv_content = view.findViewById<ProgressWebView>(com.ydl.webview.R.id.wv_content)
         close_webview_Icon = view.findViewById<View>(R.id.close_webview_Icon)
         text_title = view.findViewById<View>(R.id.text_title)
         line = view.findViewById<View>(R.id.line)
         rl_title = view.findViewById<View>(R.id.rl_title)

        close_webview_Icon?.setOnClickListener {
            this.dismiss()
        }
        webViewInit(wv_content)

    }
    override fun setCancelable(cancelable: Boolean) {
        val dialog = dialog
        val touchOutsideView =
            dialog?.window?.decorView?.findViewById<View>(com.google.android.material.R.id.touch_outside)
        val bottomSheetView =
            dialog?.window?.decorView?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)



        if (cancelable) {
            touchOutsideView?.setOnClickListener(View.OnClickListener {
                if (dialog.isShowing) {
                    dialog.cancel()
                }
            })
            BottomSheetBehavior.from<View>(bottomSheetView!!).setHideable(true)
        } else {
            touchOutsideView?.setOnClickListener(null)
            // if false 按返回键也无法取消
//      dialog.setCancelable(false)
            BottomSheetBehavior.from<View>(bottomSheetView!!).setHideable(false)
        }

    }
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {


    val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
    dialog.setOnShowListener {
        val itemView = LayoutInflater.from(context).inflate(R.layout.confide_bottom_two,null,false)
        val layoutCall=itemView.findViewById<View>(R.id.layoutCall)
        val layoutChange=itemView.findViewById<View>(R.id.layoutChange)
        val layout_change_text=itemView.findViewById<View>(R.id.layout_change_text)
        val confide_progress=itemView.findViewById<View>(R.id.confide_progress)
        layoutCall.setOnClickListener {
            callJsFun(wv_content,"layoutCall()")
        }
        layoutChange.setOnClickListener {
            layout_change_text.visibility=View.GONE
            confide_progress.visibility=View.VISIBLE
            callJsFun(wv_content,"layoutCall()")
        }
        val layoutParams = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        ).apply { gravity= Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL }
        dialog?.window?.addContentView(itemView,layoutParams)
      val bottomSheet = (it as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout?
      val behavior = BottomSheetBehavior.from(bottomSheet!!)
        behavior.peekHeight=RxImageTool.dp2px(600f)
        //true是跳过peekHeight，直接滑下去，false是可以滑动到顶部还可以保持peekHeight在滑下去
//        behavior?.skipCollapsed=true
      behavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
        override fun onStateChanged(bottomSheet: View, newState: Int) {
            when (newState) {
                3 -> {
                    rl_title.visibility=View.VISIBLE
                    close_webview_Icon.visibility=View.VISIBLE
                    text_title.visibility=View.VISIBLE
                    line.visibility=View.GONE
                }
                1 -> {
                    rl_title.visibility=View.VISIBLE
                    close_webview_Icon.visibility=View.GONE
                    text_title.visibility=View.GONE
                    line.visibility=View.VISIBLE
                }
                4 -> {
                    rl_title.visibility=View.VISIBLE
                    line.visibility=View.VISIBLE
                }
            }
        }

        override fun onSlide(bottomSheet: View, slideOffset: Float) {}
      })
    }
    return dialog
  }
    private fun callJsFun(wv_content: ProgressWebView,funcName:String) {
        val sb = StringBuffer("javascript:")
        sb.append(funcName)
        wv_content.post {
            try {
                wv_content.loadUrl(sb.toString())
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    @SuppressLint("ClickableViewAccessibility")
    private fun webViewInit(wv_content: ProgressWebView) {
        val setting: WebSettings = wv_content?.settings!!
        //支持js
        //支持js
        setting.setJavaScriptEnabled(true)
        //设置字符编码
        //设置字符编码
        setting.setDefaultTextEncodingName("GBK")
        setting.setDomStorageEnabled(true)
        val appCachePath: String = context?.getCacheDir()?.getAbsolutePath().toString()
        setting.setAppCachePath(appCachePath)
        setting.setAllowFileAccessFromFileURLs(true)
        setting.setAppCacheEnabled(true)
        setting.setAllowFileAccess(true)
        // 解决图片不显示
        // 解决图片不显示
        setting.setBlockNetworkImage(false)

        wv_content!!.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY //滚动条风格，为0指滚动条不占用空间，直接覆盖在网页上
        val jtoJHandle = WebModularServiceUtils.getWebService()
            .getJavascripHandler(requireActivity(), tellData = TellData())

        wv_content!!.addJavascriptInterface(jtoJHandle, "javascriptHandler")
        wv_content.loadUrl("https://m.ydl.com/jy/experts/23035?v=4.0.99&uid=9404770&ts=1652787528&toConfide=1&" +
                "platform_main_theme_light=00D4DF&platform_main_theme_bright=EAFAFC&platform_main_theme=00C9E2&isFromApp=1&" +
                "id=1927&ffrom=android_zhuzhan&barHeight=81&accessToken=87cba5b57f9bb196856ade3522805c11MjIwMw&sign=" +
                "6ce496690d7d5a184935f986c3631cc2")
//        wv_content.loadUrl(jumpUrl)
        wv_content.setOnTouchListener { p0, p1 -> //canScrollVertically(-1)的值表示是否能向下滚动，false表示已经滚动到顶部
            if (!wv_content.canScrollVertically(-1)) {
                wv_content.requestDisallowInterceptTouchEvent(false);
            } else {
                wv_content.requestDisallowInterceptTouchEvent(true);
            }
            false;
        }
    }
}