package com.qimai.yttgrass

import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Display
import android.view.View
import android.webkit.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import com.bumptech.glide.Glide
import com.qimai.android.fetch.Response.Status
import com.qimai.yttgrass.adapter.ImageAdapter
import com.qimai.yttgrass.model.goodsInfoBean
import com.qimai.yttgrass.view.BaseFunc
import com.qimai.yttgrass.vm.HomeVm
import com.youth.banner.indicator.CircleIndicator
import kotlinx.android.synthetic.main.fragment_goods_detail.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class DetailFragment(contentLayoutId: Int = R.layout.fragment_goods_detail) :
    Fragment(contentLayoutId) {
    private val TAG = "DetailFragment"
    private var mIsExpand = false
    private var mCodeCurrentX = 0f
    private var mOriginX = 0f
    val mCutDownTime = 60
    var mIndex = mCutDownTime

    private lateinit var baseFunc: BaseFunc
    private val mVm: HomeVm by lazy {
        ViewModelProvider(requireActivity()).get(HomeVm::class.java)
    }

    private fun initJSExeLocaMethod() {
        baseFunc = BaseFunc(requireActivity(), webview)

// --------html调用我们本地方法-----------
        webview.addJavascriptInterface(baseFunc, "abc")
    }

    @SuppressLint("SetJavaScriptEnabled", "Recycle")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initJSExeLocaMethod()
        view?.post {
            mCodeCurrentX = getScreenWidth() - cl_mini_program_code.width - cl_mini_program_code.x
            mOriginX = cl_mini_program_code.x
        }
        countdown()
        addObserver()
        mVm.mGoodsInfo?.apply {
            if (mVm.mGoodsInfo?.content.isNullOrEmpty()) {
                ll_webview.visibility = View.GONE
            } else {
                ll_webview.visibility = View.VISIBLE
            }
            mVm.mGoodsInfo?.content?.let {
                Log.d(TAG, "onActivityCreated111: it= $it")
                val info  = it.replace("<img", "<img style='max-width:100%;height:auto;'")
                getGoodsHtml(info) }?.let {
                Log.d(TAG, "onActivityCreated: it= $it")
                webview.loadDataWithBaseURL(
                    null,
                    it,
                    "text/html",
                    "UTF-8",
                    ""
                )
            }
            val images = this.showImg
            if (!images.isNullOrEmpty()) {
                val list = ArrayList<String>()
                images.forEach {
                    if (it != null && !it.original_img.isNullOrEmpty()) {
                        list.add(it.original_img!!)
                    }
                }
                updateBanner(list)

            }


            tv_introduction.text = this.title
            tv_sub_introduction.text = this.subTitle
            if (this.subTitle.isNullOrEmpty()){
                tv_sub_introduction.visibility = View.GONE
            }
            if (!goodsId.isNullOrEmpty()) {
                //二维码图片暂不展示
              /*  mVm.getMiniProgramCode(goodsId!!).observe(viewLifecycleOwner, Observer {
                    when (it.status) {
                        Status.SUCCESS -> {

                            Glide.with(iv_mini_program_img)
                                .load(it.data?.data?.code?.img)
                                .into(iv_mini_program_img)
                        }
                        Status.ERROR -> {
                            Log.d(TAG, "onActivityCreated: error= ${it.message}")
                        }
                    }
                })*/
            }
            //把商品详情清理掉
            mVm.mGoodsInfo = null
        }


        //设置不能滑动
        webview.isHorizontalScrollBarEnabled = false
        webview.isVerticalScrollBarEnabled = false
        webview.settings.apply {
            javaScriptEnabled = true
            setSupportZoom(false)
            builtInZoomControls = false
            domStorageEnabled = true
            blockNetworkImage = false
            setAppCacheEnabled(false)
            setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN)
            cacheMode = WebSettings.LOAD_NO_CACHE
            loadsImagesAutomatically = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
            // mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        }
        webview.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                //  view?.visibility = View.VISIBLE
                Log.d(TAG, "onPageStarted: ")
            }

            override fun onPageFinished(p0: WebView?, p1: String?) {
                super.onPageFinished(p0, p1)
                Log.d(TAG, "onPageFinished: ")
              //  imgReset()
               // webview.loadUrl("javascript:abc.resize(document.body.getBoundingClientRect().height)")
            }

            override fun onReceivedError(
                p0: WebView?,
                p1: WebResourceRequest?,
                p2: WebResourceError?
            ) {
                super.onReceivedError(p0, p1, p2)
                Log.d(TAG, "onReceivedError: 1")
            }

            override fun onReceivedError(p0: WebView?, p1: Int, p2: String?, p3: String?) {
                super.onReceivedError(p0, p1, p2, p3)
                Log.d(TAG, "onReceivedError: 22")
            }

            override fun shouldOverrideUrlLoading(p0: WebView?, p1: String?): Boolean {
                Log.d(TAG, "shouldOverrideUrlLoading: url= $p1")
                if (p1 != null) {
                    p0?.loadUrl(p1)
                }
                return true
            }
        }
        //  webview.loadUrl("https://www.qmai.cn/")

        iv_back.setOnClickListener {
            Navigation.findNavController(it)
                .navigateUp()

        }
        cl_mini_program_code.setOnClickListener {

            val scaleAnination: ValueAnimator

            if (!mIsExpand) {
                scaleAnination = ValueAnimator.ofFloat(1f, 0.33f)

            } else {
                scaleAnination = ValueAnimator.ofFloat(0.33f, 1f)
            }
            mIsExpand = !mIsExpand
            val animationSet = AnimatorSet()
            animationSet.play(scaleAnination)
            scaleAnination.addUpdateListener {
                val value: Float = it.animatedValue as Float
                cl_mini_program_code.scaleX = value
                cl_mini_program_code.scaleY = value
                Log.d(TAG, "onActivityCreated: value= $value")
                /* if (value == 1f) {
                     cl_mini_program_code.x =
                         (getScreenWidth() - mCodeCurrentX - cl_mini_program_code.width*0.6).toFloat()
                 }else if (value==0.33f){
                     cl_mini_program_code.x = mOriginX
                 }*/
                /* scaleAnination.addListener(object : Animator.AnimatorListener {
                     override fun onAnimationStart(p0: Animator?) {
                     }

                     override fun onAnimationEnd(p0: Animator?) {
                     }

                     override fun onAnimationCancel(p0: Animator?) {
                     }

                     override fun onAnimationRepeat(p0: Animator?) {
                     }
                 })*/
            }
            animationSet.duration = 500
            animationSet.start()
        }
    }

    private fun addObserver() {
        mVm.mClickMutator.observe(viewLifecycleOwner, Observer {
            if (it) {
                mVm.mClickMutator.value = false
                mIndex = mCutDownTime
            }
        })

        mVm.mCodeMutableList.observe(viewLifecycleOwner, Observer<String> {
            if (!it.isNullOrEmpty()) {
                // Toast.makeText(requireActivity(), it, Toast.LENGTH_LONG).show()
                Log.d("value111", "addObserver: value = $it")
                val newValue = it
                mVm.mCodeMutableList.value = ""
                mVm.getGoodsInfo(newValue, "0", "44764")
                    .observe(requireActivity(), Observer {
                        when (it.status) {
                            Status.SUCCESS -> {
                                val goods = goodsInfoBean(
                                    it.data?.data?.goods?.images,
                                    it.data?.data?.name,
                                    it.data?.data?.goods?.content?.subheading,
                                    it.data?.data?.goods?.content?.content,
                                    it.data?.data?.goods_id
                                )
                                mVm.mGoodsInfo = goods
                                Navigation.findNavController(banner)
                                    .navigate(R.id.action_detailFragment_self)
                            }
                            Status.ERROR -> {
                                Toast.makeText(requireActivity(), it.message, Toast.LENGTH_LONG)
                                    .show()
                            }
                        }
                    })
            }
        })

    }

    private fun imgReset() {
        webview.loadUrl(
            "javascript:(function(){" +
                    "var objs = document.getElementsByTagName('img'); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "var img = objs[i];   " +
                    " img.style.maxWidth = '100%';img.style.height='auto';" +
                    "}" +
                    "})()"
        )
    }

    private fun getGoodsHtml(content: String): String {
        return "<html> <body> <style>\n" +
                "        * {\n" +
                "            margin: 0;\n" +
                "            padding: 0\n" +
                "        }\n" +
                "        p {\n" +
                "            font-size: 0;\n" +
                "        }\n" +
                "        img{\n" +
                "            width: 100%;\n" +
                "            vertical-align: top;\n" +
                "        }\n" +
                "    </style>${content}</body></html>"
    }

    private fun countdown() {
        lifecycleScope.launch(Dispatchers.IO) {
            while (mIndex != 0) {
                delay(1000)
                mIndex--
                //倒计时结束返回上一页面
                if (mIndex == 0) {
                    //mBackMutableLiveData.postValue(true)
                    withContext(Dispatchers.Main) {
                        view?.let {
                            Navigation.findNavController(it)
                                .navigateUp()
                        }
                    }

                }
            }

        }
    }

    private fun getScreenWidth(): Float {
        val display: Display = requireActivity().getWindowManager().defaultDisplay
        return display.getWidth().toFloat()
    }

    private fun updateBanner(datas: ArrayList<String>?) {
        if (datas.isNullOrEmpty()) {
            return
        }
        banner.addBannerLifecycleObserver(this)
            .setIndicator(CircleIndicator(requireContext()))
            .setLoopTime(10000)
            .adapter = ImageAdapter(datas)



    }
}