package com.zj365.dc.fragment

import android.content.Intent
import android.provider.Settings
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.lifesense.android.ble.core.application.ApplicationContext
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xty.base.fragment.BaseVmFrag
import com.xty.common.Const
import com.xty.common.MMkvHelper
import com.xty.common.UmengEventId
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.AgainSignEvent
import com.xty.common.event.ChangeFamilyEvent
import com.xty.common.event.FamilyEvent
import com.xty.common.event.LoginOrRegisterEvent
import com.xty.common.event.LoginOutEvent
import com.xty.common.event.MyInfoEvent
import com.xty.common.onEventObject
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.xty.network.model.BannerBean
import com.xty.network.model.FamilyBean
import com.xty.network.model.HomeLayoutBean
import com.xty.network.model.ScienceBean
import com.youth.banner.indicator.RoundLinesIndicator
import com.youth.banner.listener.OnPageChangeListener
import com.zj365.dc.R
import com.zj365.dc.adapter.BannerCustomAdapter
import com.zj365.dc.adapter.FamilyAdapter
import com.zj365.dc.adapter.HomeContentLayoutAdapter
import com.zj365.dc.adapter.HomeTopLayoutAdapter
import com.zj365.dc.adapter.ScienceAdapter
import com.zj365.dc.adapter.holder.VideoHolder
import com.zj365.dc.databinding.FragHealthBinding
import com.zj365.dc.vm.HomeVm
import com.zj365.dc.weight.AgainSignDialog
import com.zj365.health.weight.DialogTip
import com.zj365.mime.weight.NoticeSettingDialog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.chunyu.call_kit.CallKit
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 健康*/


class
HealthHomeFrag : BaseVmFrag<HomeVm>() {

    val binding by lazy { FragHealthBinding.inflate(layoutInflater) }

    private var canGoto24Healthresult: Boolean = true
    private var isDemonstrate: Boolean = false

    //家人列表适配器
    private val mFamilyAdapter by lazy { FamilyAdapter() }

    private val mBannerAdapter by lazy { BannerCustomAdapter(requireContext()) }

    private val mMiddleBannerAdapter by lazy { BannerCustomAdapter(requireContext()) }
    private var showIdInfo = "" //需要显示的信息的id

    private var showFamily: FamilyBean? = null
    override fun setViewModel() = HomeVm()

    var defaultFamilyList = ArrayList<FamilyBean>()


    val adapterSince by lazy { ScienceAdapter() }

    val layoutTopAdapter by lazy { HomeTopLayoutAdapter(requireContext()) }

    val layoutContentAdapter by lazy { HomeContentLayoutAdapter(requireContext()) }



    private val dialogBind by lazy {
        DialogTip(requireContext(), "需绑定中健三六五健康手表，才能查看", "去绑定") {
            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE)
        }
    }
    override fun setLayout(): View = binding.root
    override fun initView() {
        super.initView()
        statusBar(binding.statusBar)

        initFamilyAdapter()
        request()
        refresh()

        binding.mBanner.addBannerLifecycleObserver(this)
            .setAdapter(mBannerAdapter)
            .setIndicator(RoundLinesIndicator(context))
            .setIndicatorSelectedWidth(dp2px(15))
            .addOnPageChangeListener(onPageChangeListener)

        binding.mBannerTwo.addBannerLifecycleObserver(this)
            .setAdapter(mMiddleBannerAdapter)
            .setIndicator(RoundLinesIndicator(context))
            .setIndicatorSelectedWidth(dp2px(15))
            .addOnPageChangeListener(onPageChangeListener)

        mBannerAdapter.setOnBannerListener { data, position ->
            var bannerBean = data as BannerBean
            onEventObject(
                requireContext(),
                UmengEventId.Banner,
                "type:${bannerBean.bannerType}; 标题:${bannerBean.title}"
            )
            when (bannerBean.bannerType) {
                1 -> {//图片

                }

                5 -> { //内部跳转
                    bundle.clear()
                    bundle.putString("title", bannerBean.title)
                    bundle.putString("url", bannerBean.linkAddress)
                    RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                }

                15 ->{ //视频跳转

                }

                10 -> {//web 跳转
                    bundle.clear()
                    bundle.putString("title", bannerBean.title)
                    bundle.putString("url", bannerBean.linkAddress)
                    RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                }
                20 ->{
                    val appId = "wx032bacb749c0dcb0" // 填移动应用(App)的 AppId，非小程序的 AppID

                    val api = WXAPIFactory.createWXAPI(requireContext(), appId)

                    val req = WXLaunchMiniProgram.Req()
                    req.userName = bannerBean.wxId// 填小程序原始id

                    req.path = bannerBean.linkAddress ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

                    if(bannerBean.wxType == 3){
                        req.miniprogramType =
                            WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                    }else{
                        req.miniprogramType =
                            WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
                    }

                    api.sendReq(req)
                }

                else ->{

                }
            }
        }

        mMiddleBannerAdapter.setOnBannerListener { data, position ->
            var bannerBean = data as BannerBean
            onEventObject(
                requireContext(),
                UmengEventId.Banner,
                "type:${bannerBean.bannerType}; 标题:${bannerBean.title}"
            )
            when (bannerBean.bannerType) {
                1 -> {//图片

                }

                5 -> { //内部跳转
                    bundle.clear()
                    bundle.putString("title", bannerBean.title)
                    bundle.putString("url", bannerBean.linkAddress)
                    RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                }

                10 -> {//web 跳转
                    bundle.clear()
                    bundle.putString("title", bannerBean.title)
                    bundle.putString("url", bannerBean.linkAddress)
                    RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                }

                15 ->{ //视频跳转

                }

                20 ->{
                    val appId = "wx032bacb749c0dcb0" // 填移动应用(App)的 AppId，非小程序的 AppID

                    val api = WXAPIFactory.createWXAPI(requireContext(), appId)

                    val req = WXLaunchMiniProgram.Req()
                    req.userName = bannerBean.wxId // 填小程序原始id

                    req.path = bannerBean.linkAddress ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

                    if(bannerBean.wxType == 3){
                        req.miniprogramType =
                            WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                    }else{
                        req.miniprogramType =
                            WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
                    }

                    api.sendReq(req)
                }
                else ->{

                }
            }
        }
        setOnClickListener()
//        updateWarningStatus()
        initAdapter()
    }

    private fun initAdapter() {
        binding.mRecycleNews.layoutManager = LinearLayoutManager(requireContext())
        binding.mRecycleNews.adapter = adapterSince
        adapterSince.setOnItemClickListener { adapter, view, position ->
            bundle.clear()
            var bean = adapter.getItem(position) as ScienceBean
            bundle.putSerializable("bean", bean)
            onEventObject(requireContext(), UmengEventId.HealthScience, "${bean.name}")
            RouteManager.goAct(ARouterUrl.SCIENCE_DETAIL, bundle)

        }

        binding.mCom.rvLayout.layoutManager= LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false)
        binding.mCom.rvLayout.adapter = layoutTopAdapter
        layoutTopAdapter.setOnItemClickListener { adapter, view, position ->


            var contentData = adapter.getItem(position) as HomeLayoutBean.HomeChildBean
            when(contentData.jumpType){
                1 ->{

                    when(contentData.jumpUrl){
                        "health_data" ->{
                            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                            }else {
                                RouteManager.goAct(ARouterUrl.FAMILY_RECORD_ACT)
                            }
//                            CommonToastUtils.showToast("敬请期待")
                        }
                        "health_dic" ->{
                            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                                RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                            }else {
                                RouteManager.goAct(ARouterUrl.HEALTH_CODE_MAIN_ACT)
                            }
                      //      CommonToastUtils.showToast("敬请期待")

                        }
                        else ->{
                            CommonToastUtils.showToast("敬请期待")

                        }
                    }

                }

                2->{
                    if (contentData.name == "视频问诊"){
                        if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                            RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                        }else {
                            mViewModel.getVideoDoctorType()
                        }

                    }else{
                        contentData.jumpUrl?.let {
                            bundle.clear()
                            bundle.putString("title", contentData.name)
                            bundle.putString("url", contentData.jumpUrl)
                            RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                        }
                    }


                }

                3 ->{
                    contentData.jumpUrl?.let {
                        val appId = "wx032bacb749c0dcb0" // 填移动应用(App)的 AppId，非小程序的 AppID

                        val api = WXAPIFactory.createWXAPI(requireContext(), appId)

                        val req = WXLaunchMiniProgram.Req()
                        req.userName = contentData.wxId // 填小程序原始id

                        req.path = contentData.jumpUrl ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

                        if(contentData.wxType == 3){
                            req.miniprogramType =
                                WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                        }else{
                            req.miniprogramType =
                                WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
                        }

                        api.sendReq(req)
                    }

                }

                4 ->{
                    CommonToastUtils.showToast("敬请期待")
                }

                else ->{

                }
            }
        }


        binding.mChildView.homeContentRv.adapter = layoutContentAdapter
        layoutContentAdapter.setOnItemClickListener { adapter, view, position ->

                var contentData = adapter.getItem(position) as HomeLayoutBean.HomeChildBean
                when(contentData.jumpType){
                    1 ->{
                        contentData.jumpUrl?.let {
                            when(contentData.jumpUrl){
                                "AI_TONGUE" ->{ //AI 舌诊
                                    if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                                        RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                                    }else {
                                        bundle.clear()
                                        bundle.putString("id", showIdInfo)
                                        RouteManager.goAct(ARouterUrl.TONGUE_MAIN_ACTIVITY, bundle)
                                    }
                                }

                                "AI_TUMOR" ->{ //防癌
                                    if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                                        RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                                    }else {
                                        bundle.clear()
                                        bundle.putString("id", showIdInfo)
                                        RouteManager.goAct(ARouterUrl.PRVENT_CANCER, bundle)
                                    }
                                }

                                "MEALS"->{ //膳食管理
                                        bundle.clear()
                                        bundle.putString("userId", showIdInfo)
                                        RouteManager.goAct(ARouterUrl.DIET_MANAGEMENT, bundle)

                                }

                                "PSYCHOLOGY" ->{
                                    if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                                        RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                                    }else {
                                        RouteManager.goAct(ARouterUrl.PSYCHOLOGICAL_TEST_LIST_ACT)
                                    }
//                                    CommonToastUtils.showToast("敬请期待")
                                }

                                "AI_SUGAR_MEDICINE" ->{
                                    if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
                                        RouteManager.goAct(ARouterUrl.LOGIN_ACT)
                                    }else {
                                        bundle.clear()
                                        bundle.putInt("type", 1)
                                        RouteManager.goAct(
                                            ARouterUrl.AI_SKIN_MEASUREMENT_ACTIVITY,
                                            bundle
                                        )
                                    }

                                }
                                "AI_SKIN" ->{

                                }

                                else ->{
                                    CommonToastUtils.showToast("敬请期待")
                                }
                            }
                        }

                    }

                    2->{
                        contentData.jumpUrl?.let {
                            bundle.clear()
                            bundle.putString("title", contentData.name)
                            bundle.putString("url", contentData.jumpUrl)
                            RouteManager.goAct(ARouterUrl.WEB_ACT, bundle)
                        }

                    }

                    3 ->{
                        contentData.jumpUrl?.let {
                            val appId = "wx032bacb749c0dcb0" // 填移动应用(App)的 AppId，非小程序的 AppID

                            val api = WXAPIFactory.createWXAPI(requireContext(), appId)

                            val req = WXLaunchMiniProgram.Req()
                            req.userName = contentData.wxId // 填小程序原始id

                            req.path = contentData.jumpUrl ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                            if(contentData.wxType == 3){
                                req.miniprogramType =
                                    WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                            }else{
                                req.miniprogramType =
                                    WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
                            }


                            api.sendReq(req)
                        }

                    }

                    4 ->{
                        CommonToastUtils.showToast("敬请期待")
                    }

                    else ->{

                    }
                }
        }

    }


    private var onPageChangeListener = object : OnPageChangeListener {
        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
        }

        override fun onPageSelected(position: Int) {
            var viewHolder = binding.mBanner.adapter.viewHolder
            if (viewHolder is VideoHolder) {
                var player = viewHolder.player
                player.setVideoAllCallBack(object : VideoAllCallBack {
                    override fun onStartPrepared(url: String?, vararg objects: Any?) {
                    }

                    override fun onPrepared(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickStartIcon(url: String?, vararg objects: Any?) {
                        binding.mBanner.stop()
                        binding.mBanner.isAutoLoop(false)
                    }

                    override fun onClickStartError(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickStop(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickStopFullscreen(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickResume(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickResumeFullscreen(
                        url: String?,
                        vararg objects: Any?
                    ) {
                    }

                    override fun onClickSeekbar(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickSeekbarFullscreen(
                        url: String?,
                        vararg objects: Any?
                    ) {
                    }

                    override fun onAutoComplete(url: String?, vararg objects: Any?) {
                        println("Test----------onAutoComplete url:$url;objects$objects")
                        binding.mBanner.isAutoLoop(true)
                        binding.mBanner.start()
                    }

                    override fun onEnterFullscreen(url: String?, vararg objects: Any?) {
                    }

                    override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                    }

                    override fun onQuitSmallWidget(url: String?, vararg objects: Any?) {
                    }

                    override fun onEnterSmallWidget(url: String?, vararg objects: Any?) {
                    }

                    override fun onTouchScreenSeekVolume(
                        url: String?,
                        vararg objects: Any?
                    ) {
                    }

                    override fun onTouchScreenSeekPosition(
                        url: String?,
                        vararg objects: Any?
                    ) {
                    }

                    override fun onTouchScreenSeekLight(
                        url: String?,
                        vararg objects: Any?
                    ) {
                    }

                    override fun onPlayError(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickStartThumb(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickBlank(url: String?, vararg objects: Any?) {
                    }

                    override fun onClickBlankFullscreen(
                        url: String?,
                        vararg objects: Any?
                    ) {
                    }

                })
            }
        }

        override fun onPageScrollStateChanged(state: Int) {
        }
    }

    private fun setOnClickListener() {

        binding.tvMore.setOnClickListener {
            RouteManager.goAct(ARouterUrl.SCIENCE_LIST)
        }
    }


    // 刷新注册
    private fun refresh() {
        refresh.setRefresh(binding.mRefresh) {
            request()
        }
    }

    private fun request() {
        mainScope.launch {
            mViewModel.getBanners(CommonUtils.getMyUserId(),1)//当期登录用户id

            delay(1000)

            mViewModel.getBanners(CommonUtils.getMyUserId(),2)//当期登录用户id


        }


        mViewModel.getScinceList()

        mViewModel.getHomeLayout()

    }


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

    override fun observer() {

        //首页轮播图
        mViewModel.bannerLive.observe(this) {
            if (null == it) {
                return@observe
            }
            if (it[1].isNullOrEmpty()){
                binding.mBanner.visibility = View.GONE
            }else{
                binding.mBanner.visibility = View.VISIBLE

                mBannerAdapter.setDatas(it[1])
            }
            if(it[2].isNullOrEmpty()){
                binding.mBannerCardTwo.visibility = View.GONE

            }else{
                binding.mBannerCardTwo.visibility = View.VISIBLE
                mMiddleBannerAdapter.setDatas(it[2])
            }



        }

        mViewModel.scinceLive.observe(this) {
            adapterSince.setNewInstance(it.data)
        }
        mViewModel.layoutLive.observe(this){
            layoutTopAdapter.setNewInstance(it.data.top)
            if(it.data.middle.size <= 6){
                binding.mChildView.homeContentRv.layoutManager = GridLayoutManager(requireContext(),3)

            }else{
                binding.mChildView.homeContentRv.layoutManager = GridLayoutManager(requireContext(),4)

            }
            layoutContentAdapter.setNewInstance(it.data.middle)
        }

        mViewModel.videoDoctorLive.observe(this){
            if (it.data.type == 2){
                CallKit.startCallKitLogic(requireActivity(),it.data.url)
            }else{
                val appId = "wx032bacb749c0dcb0" // 填移动应用(App)的 AppId，非小程序的 AppID

                val api = WXAPIFactory.createWXAPI(requireContext(), appId)

                val req = WXLaunchMiniProgram.Req()
                req.userName = it.data.wxid // 填小程序原始id

                req.path = it.data.url ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                if(it.data.wxtype== 1){
                    req.miniprogramType =
                        WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
                  }else{
                      req.miniprogramType =
                          WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
                  }

                api.sendReq(req)
            }
        }
    }


    private fun initFamilyAdapter() {

        defaultFamilyList.add(0, FamilyBean().apply {
            this.fCall = "我"
        })

        defaultFamilyList.add(1, FamilyBean().apply {
            this.fCall = "家人"
        })

        binding.mCom.mRecycle.layoutManager =
            LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        binding.mCom.mRecycle.adapter = mFamilyAdapter
        mFamilyAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == mFamilyAdapter.data.size - 1) { //第一期暂不做

                RouteManager.goAct(ARouterUrl.FAMILY_HEALTH_ACT)
            }
        }

        mFamilyAdapter.position = 0
        mFamilyAdapter.setNewInstance(defaultFamilyList)
    }
    private val reqGpsPermissionDialog by lazy {
        NoticeSettingDialog(requireContext(), "请打开GPS权限", {

        }) {
            // 转到手机设置界面，用户设置GPS
            var intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 1001) // 设置完成后返回到原来的界面
        }
    }


    private fun requestGPSPermission() {
        reqGpsPermissionDialog.show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginOrRegisterChange(event: LoginOrRegisterEvent){
        showIdInfo =if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
            ""
        } else {
            MMkvHelper.getLong(Const.USER_ID).toString()
        }
        request()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginOutChange(event: LoginOutEvent){

    }
}
