package com.ydl.confide.home

import android.annotation.SuppressLint
import android.app.Dialog
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.widget.FrameLayout
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.alibaba.android.arouter.launcher.ARouter
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.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.ValueCallback
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.ydl.confide.R
import com.ydl.confide.home.http.ConfideHomeApi
import com.ydl.utils.WebUrlParamsUtils
import com.ydl.webview.ProgressWebView
import com.ydl.webview.TellData
import com.ydl.webview.WebModularServiceUtils
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.TimeUtil
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper.Companion.getInstance
import com.ydl.ydlnet.YDLHttpUtils
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.api.service.IImService
import com.yidianling.user.api.service.IUserService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.item_expert_intro.*

class ConfideBottomSheetDialogFragment : BottomSheetDialogFragment() {
    companion object {
        private const val KEY_JUMP_URL = "jumpUrl"
        private const val KEY_DOCTOR_ID = "doctor_id"
        private const val KEY_SHOULD_SHOW = "should_show"
    }

    lateinit var wv_content: ProgressWebView
    lateinit var text_title: TextView
    lateinit var line: View
    lateinit var rl_title: View
    lateinit var close_webview_Icon: View
    lateinit var layoutCall: View
    lateinit var layoutChange: View
    lateinit var tvCall: TextView
    lateinit var tvTime: TextView
    lateinit var first_order: View
    lateinit var confideProgress: View
    lateinit var layout_change_text: View


    lateinit var jumpUrl: String
    lateinit var doctorId: String
    var shouldShow: Boolean? = false
    lateinit var uid:String
    fun showBottomSheetDialog(
        activity: FragmentActivity,
        jumpUrl: String,
        doctorId: String,
        shouldShow: Boolean? = false
    ) {
        arguments = Bundle().apply {
            putString(KEY_JUMP_URL, jumpUrl)
            putString(KEY_DOCTOR_ID, doctorId)
            shouldShow?.let { putBoolean(KEY_SHOULD_SHOW, it) }
        }
        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) ?: ""
        doctorId = arguments?.getString(KEY_DOCTOR_ID) ?: ""
        shouldShow = arguments?.getBoolean(KEY_SHOULD_SHOW) ?: false
        onLoadDialStatus(doctorId)
//        +
        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<TextView>(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)
            layoutCall = itemView.findViewById<View>(R.id.layoutCall)
            layoutChange = itemView.findViewById<View>(R.id.layoutChange)
            confideProgress = itemView.findViewById<View>(R.id.confide_progress)
            layout_change_text = itemView.findViewById<View>(R.id.layout_change_text)
            tvCall = itemView.findViewById<TextView>(R.id.tvCall)
            tvTime = itemView.findViewById<TextView>(R.id.tvTime)
            first_order = itemView.findViewById<TextView>(R.id.first_order)
            val isLogin = findRouteService(IUserService::class.java)?.isLogin() ?: false
            first_order.visibility = if (isLogin) View.GONE else View.VISIBLE
            if (shouldShow == true) {
                layoutChange.visibility = View.VISIBLE
            } else {
                layoutChange.visibility = View.GONE
            }
            layoutCall.setOnClickListener {
                callJsFun(wv_content, "listenCallClick()")
            }
            layoutChange.setOnClickListener {
                layout_change_text.visibility = View.GONE
                confideProgress.visibility = View.VISIBLE
                callJsFun(wv_content, "handleNext()")
            }
            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()
            }
        }
    }
    fun updateChange(doctorId: String,title:String,uid: String){
        this.uid=uid
        text_title.text=title
        confideProgress.visibility=View.GONE
        layout_change_text.visibility=View.VISIBLE
        onLoadDialStatus(doctorId)
        callJsFun(wv_content,"setUnRead(${getUnReadByUid(uid =uid )})")
    }
    @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")
        var jumpurl = "http://192.168.210.152/jy/listenMask?listenerId=257&isFromApp=1"
        var url = WebUrlParamsUtils.getSuffix(jumpurl, jtoJHandle.getUriAppendSuffix())
        LogUtil.e("AAA" + url)
        wv_content.loadUrl(url)

//        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;
        }
        wv_content.webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(
                webView: WebView,
                s: String,
                s1: String,
                jsResult: JsResult
            ): Boolean {
                return super.onJsAlert(webView, s, s1, jsResult)
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    wv_content.progressbar.visibility = View.GONE
                    callJsFun(wv_content,"setUnRead(${getUnReadByUid(uid =uid )})")
                } else {
                    if (wv_content.progressbar.visibility == View.GONE) {
                        wv_content.progressbar.visibility = View.VISIBLE
                    }
                    wv_content.progressbar.progress = newProgress
                }
                super.onProgressChanged(view, newProgress)
            }

            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
               text_title.text=title
            }

            // For Android < 3.0
            fun openFileChooser(valueCallback: ValueCallback<Uri?>) {
            }

            // For Android  >= 3.0
            fun openFileChooser(valueCallback: ValueCallback<*>, acceptType: String?) {
            }

            //For Android  >= 4.1
            override fun openFileChooser(
                valueCallback: ValueCallback<Uri>,
                acceptType: String,
                capture: String
            ) {
            }

            // For Android >= 5.0
            override fun onShowFileChooser(
                webView: WebView,
                filePathCallback: ValueCallback<Array<Uri>>,
                fileChooserParams: FileChooserParams
            ): Boolean {
                return true
            }
        }
    }
    fun getUnReadByUid(uid:String):Int{
        return ARouter.getInstance().navigation(IImService::class.java).getUnReadByUid(uid)
    }
    @SuppressLint("CheckResult")
    private fun onLoadDialStatus(doctorId: String) {
        val confideApi = YDLHttpUtils.obtainApi(ConfideHomeApi::class.java)
        confideApi.getDialStatus(doctorId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.code == "200") {
                    layoutCall.visibility = View.VISIBLE
                    val lineStatus = resp.data?.confideLine ?: 2
                    /*
                    * 1在线 2离线 3通话中 4 继续倾诉
                    * */
                    when (lineStatus) {
                        1 -> {
                            tvCall.text = "立即拨打"
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_1)
                        }
                        2 -> {
                            tvCall.text = "已离线"
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_2)
                        }
                        3 -> {
                            tvCall.text = "通话中"
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_3)
                        }
                        4 -> {
                            tvCall.text = "继续倾诉"
                            layoutCall.background =
                                context?.getDrawable(R.drawable.confide_line_bg_1)
                                context?.getDrawable(R.drawable.confide_line_bg_1)
                            val t = resp?.data?.remainingTime?.remainingTime
                            if (t != null) {
                                tvTime.visibility = View.VISIBLE
                                val remain = TimeUtil.getElapseTimeForShow(t * 1000)
                                tvTime.text = "(剩余" + remain + ")"
                            }

                        }
                    }
                } else {
                    if (!resp.msg.isNullOrEmpty()) {
                        ToastUtil.toastShort(resp.msg)
                    }
                }
            }, { throwable -> throwable.printStackTrace() })
    }
}