package com.yidianling.uikit.custom.widget.expertConsultService.view

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import androidx.viewpager.widget.PagerAdapter
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.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.ydl.ydlcommon.data.http.BaseAPIResponse
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.im.R
import com.yidianling.im.api.service.IImService
import com.yidianling.im.bean.BusyBean
import com.yidianling.im.router.ImIn
import com.yidianling.im.session.extension.CustomAttachSubScriptTime
import com.yidianling.uikit.business.session.helper.MessageListPanelHelper
import com.yidianling.uikit.custom.bridge.ActionHandlerStorage
import com.yidianling.uikit.custom.http.ServiceImpl
import com.yidianling.uikit.custom.http.ServiceImpl.Companion.instance
import com.yidianling.uikit.custom.http.response.ServiceItemBean
import com.yidianling.uikit.custom.widget.expertConsultService.callback.ConsultServiceViewCallback
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.im_expert_consult_service_list_dialog_layout.dialog_bottom_scroll_view
import kotlinx.android.synthetic.main.im_expert_consult_service_list_fragment_layout.*

class ExpertConsultServiceListDialog2(
    val mContext: Context, val mList: List<ServiceItemBean>?, val mIsBusy: Boolean,
    val toUid: String, val doctorID: String
) : BottomSheetDialogFragment() {

    private var mConsultServiceListView: ExpertConsultServiceView? = null
    private var mWebviewView: ExpertConsultWebview? = null
    private var mViewList: ArrayList<View> = ArrayList()
    private var mSelectType: String = "全部"


    var bottomSheet: FrameLayout? = null
    private var behavior: BottomSheetBehavior<*>? = null
    fun changeItem() {
        dialog_bottom_scroll_view.currentItem = 0
    }

    @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.im_expert_consult_service_list_fragment_layout,
            container,
            false
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        var typeList: ArrayList<String> = ArrayList()
        typeList.add(mSelectType)//默认选中


        if (mList != null) {
            dialog_ll_empty.visibility=View.GONE
            mList.forEach { item ->
                typeList.add(item.cateName)
            }
            onViewCreate(typeList, mList)
        } else {
            ServiceImpl.instance.serviceList(doctorID)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer<BaseAPIResponse<List<ServiceItemBean>>> { res: BaseAPIResponse<List<ServiceItemBean>> ->
                    if (res.data != null && res.data.size > 0) {
                        dialog_ll_empty.visibility=View.GONE
                        var serviceItemBeanList = res.data

                        serviceItemBeanList.forEach { item ->
                            typeList.add(item.cateName)
                        }

                        onViewCreate(typeList, serviceItemBeanList)
                        // 获取专家是否在繁忙状态
                        instance.queryDoctorIsBusy(doctorID)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(
                                { res: BaseAPIResponse<BusyBean> ->
                                    var isBusy = res.data.success
                                    mConsultServiceListView?.setBusyStatus(isBusy)
                                }
                            ) { throwable: Throwable? -> }


                    } else {
                        dialog_ll_empty.visibility=View.VISIBLE
                    }
                }, Consumer { throwable: Throwable? -> })
        }


    }

    private fun onViewCreate(typeList: ArrayList<String>, mList: List<ServiceItemBean>) {
        mConsultServiceListView = ExpertConsultServiceView(mContext, mIsBusy)

        (mConsultServiceListView as ExpertConsultServiceView).setDataAndClick(
            typeList,
            mList,
            object :
                ConsultServiceViewCallback {
                override fun onCloseClick() {
                    dismiss()
                }

                override fun onItemClick(serviceBean: ServiceItemBean.ProductsBean) {
                    mWebviewView?.setData(serviceBean)
                    dialog_bottom_scroll_view.currentItem = 1
                }

                override fun addTime() { // 提醒添加时间回调


                    if (!ImIn.isLogin(requireActivity(),true)){
                        return
                    }
                    // 埋点

                    if (ActionHandlerStorage.getL(toUid) != null){
                        ActionCountUtils.baiDuCountSign3(
                            "ydl_user_product_page", "remind_add_click", toUid,
                            ActionHandlerStorage.getL(toUid).info.name, ""
                        )
                    }
                    // 发送提醒消息
                    val customTime = CustomAttachSubScriptTime("我想预约服务，请尽快开启服务时间")
                    val message = MessageBuilder.createCustomMessage(
                        toUid,
                        SessionTypeEnum.P2P,
                        "我想预约服务，请尽快开启服务时间",
                        customTime
                    )
                    NIMClient.getService(MsgService::class.java).sendMessage(message, false)
                        .setCallback(object :
                            RequestCallback<Void> {
                            override fun onSuccess(param: Void?) {
                                MessageListPanelHelper.getInstance().notifyAddMessage(message)
                                ARouter.getInstance().navigation(IImService::class.java)
                                    ?.startChatBySessionId(requireActivity(), toUid!!)
                                dismiss()
                            }

                            override fun onException(exception: Throwable?) {
                                dismiss()
                            }

                            override fun onFailed(code: Int) {
                                dismiss()
                            }
                        })
                }
            })

        consult_service_dialog_close.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    behavior?.isHideable = true
                }
            }
            true
        }
        mViewList.add(mConsultServiceListView as View)
        mWebviewView = ExpertConsultWebview(mContext, doctorID = doctorID)
        mViewList.add(mWebviewView as View)

        dialog_bottom_scroll_view.adapter = ConsultServicePagerAdapter()
        dialog_bottom_scroll_view.currentItem = 0
    }


    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 layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
            ).apply { gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL }

            bottomSheet =
                (it as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout?
            behavior = BottomSheetBehavior.from(bottomSheet!!)
            behavior?.peekHeight = RxDeviceTool.getScreenHeight(mContext) - RxImageTool.dp2px(100f)

            behavior?.isHideable = false

            setMaxHeight(RxDeviceTool.getScreenHeight(mContext) - RxImageTool.dp2px(100f))
            //true是跳过peekHeight，直接滑下去，false是可以滑动到顶部还可以保持peekHeight在滑下去
//        behavior?.skipCollapsed=true

            behavior?.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
                override fun onStateChanged(bottomSheet: View, newState: Int) {
                    when (newState) {
                        BottomSheetBehavior.STATE_EXPANDED -> {
                            behavior?.state = BottomSheetBehavior.STATE_COLLAPSED
                            behavior?.isHideable = false
                        }
                        BottomSheetBehavior.STATE_DRAGGING -> {
                        }
                        BottomSheetBehavior.STATE_COLLAPSED -> {
                            behavior?.isHideable = false
                        }
                    }
                }

                override fun onSlide(bottomSheet: View, slideOffset: Float) {}
            })
        }
        return dialog
    }

    private fun setMaxHeight(height: Int) {
        bottomSheet?.layoutParams?.height = height
        bottomSheet?.requestLayout()
    }


    internal inner class ConsultServicePagerAdapter : PagerAdapter() {

        override fun getCount(): Int {
            return mViewList.size
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view === `object`
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val view = mViewList[position]
            container.addView(view)
            return view
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }
    }

    fun show() {
        if (mContext is FragmentActivity) {
            show(mContext.supportFragmentManager, "consult_bottom_showdialog")
        }

    }
}