package com.zswc.creativity.activity

import android.graphics.Color
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.lifecycleScope
import coil.ImageLoader
import coil.decode.GifDecoder
import coil.decode.ImageDecoderDecoder
import coil.load
import coil.request.Disposable
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.qmuiteam.qmui.kotlin.onClick
import com.ysnows.base.utils.B
import com.ysnows.base.utils.UiSwitch
import com.ysnows.base.utils.UiUtils
import com.zswc.creativity.R
import com.zswc.creativity.base.MBActivity
import com.zswc.creativity.config.ConfigRx
import com.zswc.creativity.databinding.ActivityTibetanDetailsBinding
import com.zswc.creativity.model.bean.PayTypeBen
import com.zswc.creativity.utils.ColorUtils
import com.zswc.creativity.utils.net.NetEngine
import com.zswc.creativity.view.MyScrollView
import com.zswc.creativity.vmodel.TibetanDetailsVModel
import kotlinx.coroutines.launch
import java.text.DecimalFormat

/**
 * 藏品详情
 *on 2022/7/23
 */
class TibetanDetailsActivity : MBActivity<TibetanDetailsVModel, ActivityTibetanDetailsBinding>() {

    var sumSecond = 300//5分钟的总的秒数
    var disposable: Disposable? = null
     var islide = true //是否滑动的时候标题改变
     var screenHeightPixels = 0


    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        titleBar()?.imgRight?.setImageResource(R.drawable.ct_share)
        screenHeightPixels = UiUtils.getScreenHeightPixels()
        setShow()


        vm.ll = binding.ll
        var id = intent?.extras?.getString("id")
        vm.getInfo(id!!)

        vm.data.observe(this) {

            //设置详情图片

            binding.imgDeatils.load(it.describe[0])


            if (!TextUtils.isEmpty(it.detail_img)) {
                //获取文件后缀
                var ss = it.detail_img.substring(it.detail_img.length - 3, it.detail_img.length);

                if (ss == "gif" || ss == "GIF") {
                    binding.imageView.visibility = View.GONE
                    //设置图片加载gif
                    val imageLoader = ImageLoader.Builder(context = this)
                            .crossfade(true)
                            .availableMemoryPercentage(0.25)
                            .allowRgb565(true)
                            .componentRegistry {
                                if (SDK_INT > 28) {
                                    add(ImageDecoderDecoder())
                                } else {
                                    add(GifDecoder())
                                }
                            }.build()
                    disposable = binding.imageGifView.load(it.detail_img, imageLoader)
                    binding.imageGifView.visibility = View.VISIBLE
                } else {
                    binding.imageView.load(it.detail_img)
                    binding.imageView.visibility = View.VISIBLE
                    binding.imageGifView.visibility = View.GONE
                }
            }


        }


    }

    private fun setShow() {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { //不支持沉浸式状态栏
        } else {
            //获取状态栏的高度
            val statusBarHeight: Int = UiUtils.getStatusBarHeight()

            //动态设置高度  tv
            val params = binding.tv.getLayoutParams()
            //获取当前控件的布局对象
            //params.height=UiUtils.dp2dip(getContext(), statusBarHeight);//设置当前控件布局的高度
            params.height = statusBarHeight
            binding.tv.layoutParams = params //将设置好的布局参数应用到控件中
            binding.tv.visibility = View.VISIBLE

            binding.tvTwo.layoutParams=params
            binding.tvTwo.visibility = View.VISIBLE


        }

    }



    override fun listeners() {
        super.listeners()




        binding.scroll.setOnScrollListener(object : MyScrollView.OnScrollChangedListener {


            override fun onScrollChanged(x: Int, y: Int, oldX: Int, oldY: Int) {
                if (islide) {

                    if (y == 0) {
                        binding.llShowTwo.visibility=View.GONE
                        binding.llShowOne.visibility=View.VISIBLE

                    } else if (y - oldY > 0) {
                        if (screenHeightPixels <= 960) {
                            setBarVisibility(y, 100)
                        } else {
                            setBarVisibility(y, 200)
                        }
                    } else if (y - oldY < 0) {
                    }
                }
            }
        })



        titleBar()?.imgLeft?.onClick {

            finishActivity()
        }

        binding.butBuy.onClick {

            vm.toBuy(binding.butBuy)
        }
        binding.imgShare.onClick {
            //分享
            vm.getUrl()

        }
        binding.imgShareTo.onClick {
            //分享
            vm.getUrl()
        }


//        screenHeightPixels = UiUtils.getScreenHeightPixels(getContext());
//
//        obscroll.setOnScrollListener(object : OnScrollChangedListener() {
//            /**
//             * @param x
//             * @param y
//             * @param oldX
//             * @param oldY
//             */
//            fun onScrollChanged(x: Int, y: Int, oldX: Int, oldY: Int) {
//                if (islide) {
//                    if (affix_type != null && affix_type.equals("3")) {
//                        return
//                    }
//                    if (y == 0) {
//                        tvTitleName.setVisibility(View.INVISIBLE)
//                        lineL.setAlpha(0)
//                        tvTitleName.setAlpha(1)
//                        bar.setBackgroundColor(Color.parseColor("#00000000"))
//                    } else if (y - oldY > 0) {
//                        if (screenHeightPixels <= 960) {
//                            setBarVisibility(y, 100)
//                        } else {
//                            setBarVisibility(y, 200)
//                        }
//                    } else if (y - oldY < 0) {
//                    }
//                }
//            }
//        })

    }

    private fun setBarVisibility(y: Int, height: Int) {
        if (y > 0 && y < height) {
            binding.llShowOne.visibility=View.GONE
            binding.llShowTwo.visibility=View.VISIBLE


            val df = DecimalFormat("0.00")
            val s = df.format((y.toFloat() / height).toDouble())
            val a = s.toFloat() //0~1

            // float a = y / height;//0~1
            val ratio = 255 - (255 * a).toFloat() //255-(0~255)=255~0
            val bgColor: Int = ColorUtils.getColorWithAlpha(Color.parseColor("#FFFFFF"), ratio)
            binding.llShowTwo.setBackgroundColor(bgColor)
            binding.tvShowTitle.alpha = a

        } else if (y > height) {
            binding.llShowTwo.setBackgroundColor(Color.WHITE)
            binding.llShowTwo.visibility = View.VISIBLE

            binding.tvShowTitle.alpha = 1f
            binding.tvShowTitle.visibility = View.VISIBLE
        }
    }


//    private fun setBarVisibility(y: Int, height: Int) {
//        if (y > 0 && y < height) {
//            line.setVisibility(View.GONE)
//            bar.setVisibility(View.VISIBLE)
//            val df = DecimalFormat("0.00")
//            val s: String = df.format(y.toFloat() / height)
//            val a = s.toFloat() //0~1
//
//            // float a = y / height;//0~1
//            val ratio = 255 - (255 * a).toInt() //255-(0~255)=255~0
//            val bgColor: Int = ColorUtils.getColorWithAlpha(Color.parseColor("#FFFFFF"), ratio)
//            bar.setBackgroundColor(bgColor)
//            tvTitleName.setAlpha(a)
//            line.setAlpha(a)
//        } else if (y > height) {
//            bar.setBackgroundColor(Color.WHITE)
//            bar.setVisibility(View.VISIBLE)
//            lineL.setVisibility(View.VISIBLE)
//            lineL.setAlpha(1)
//            tvTitleName.setAlpha(1)
//            tvTitleName.setVisibility(View.VISIBLE)
//        }
//    }


    override fun binding(): ActivityTibetanDetailsBinding {
        return ActivityTibetanDetailsBinding.inflate(layoutInflater)
    }

    override fun vmClass(): Class<TibetanDetailsVModel> {
        return TibetanDetailsVModel::class.java
    }

    override fun title(): String? {
        return null
    }

    override val isRxbus: Boolean
        get() = true

    //倒计时


    fun initOrderCancelTime(pay_time_long: String?) {
        //-------

        sumSecond = pay_time_long!!.toInt()

        vm.time.value = "请在 " + formatTime(sumSecond) + "内支付"


        addProgress()
    }

    private fun addProgress() {


        Log.e("-shy-", "isUp=" + vm.isUp)
        if (sumSecond == 0) {
            //结束 todo:
//            vm.isUp = false
//
//            vm.bean.value?.state = 9
            //去取消订单
            // vm.toCancerOrderTo()

        } else {
            if (vm.isUp) {
                sumSecond--
                handler.sendEmptyMessageDelayed(0x101, 1000)
            }

        }
    }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            //计算进度


            vm.time.value = "请在 " + formatTime(sumSecond) + "内支付"
            addProgress()
        }
    }

    /**
     * 将秒转化为 HH:mm:io.agora.rtc.ss 的格式
     *
     * @param time 秒
     * @return
     */
    /**
     * 将秒转化为 HH:mm:io.agora.rtc.ss 的格式
     *
     * @param time 秒
     * @return
     */
    var decimalFormat: DecimalFormat? = null

    private fun formatTime(time: Int): String? {
        if (decimalFormat == null) {
            decimalFormat = DecimalFormat("00")
        }
        val hh: String = decimalFormat!!.format(time / 3600)
        val mm: String = decimalFormat!!.format(time % 3600 / 60)
        val ss: String = decimalFormat!!.format(time % 60)
        // return "$hh:$mm:$io.agora.rtc.ss"
        return "$mm:$ss"
    }


    @Subscribe(tags = [Tag(ConfigRx.CHOSE_PAY_TYPE)])
    fun setChosePay(bean: PayTypeBen) {

        ////1支付宝 2微信  //默认支付宝  3钱包

        if (bean.choseType == 3) {

            lifecycleScope.launch {


                val it = vm.repository().lreq {
                    NetEngine.service.setCreateOrder(
                            "app", vm.data.value?.id, bean.num,
                            "qb", bean.second_password
                    )
                }
                if (it.ok(true)) {
                    //todo:支付成功
                    var price = bean.num.toInt() * vm.data.value?.price!!.toDouble()
                    var orderid = it.data.toString()
                    UiSwitch.bundle(
                            context(), PaySuessActivity::class.java,
                            B().putString("orderid", orderid)
                                    .putString("type", "2")
                                    .putString("price", price.toString())
                                    .ok()
                    )

                }

            }

        }


//        lifecycleScope.launch {
//
//            //todo:测试 0.01
//            val it = vm.repository().lreq { NetEngine.service.amountAdd("0.01",type) }
//
//            if (it.ok(false)) {
//                if (type == "1") {//支付宝
//                    val orderInfo = it.data!!.alipay
//
//                    CpAlipay.pay(vm.repository().context!!, orderInfo)
//                } else {//微信
//                    if (WeChatUtil.isWeixinAvilible(context())) {
//                        WeChatUtil.toWXPay(context(), it.data!!)
//                    }
//                }
//            }
//
//        }


    }


    @Subscribe(tags = [Tag(ConfigRx.PAY_COMPLETE)])
    fun setPayComplete(money: String) {//充值了保证金后刷新
        //刷新 todo：
        toast("支付完成")
    }

    @Subscribe(tags = [Tag(ConfigRx.PAY_COMPLETE_CLOSE)])
    fun setPayCompleteClose(type: String) {//关闭
        //刷新 todo：
        finish()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (null != disposable) {
                disposable?.dispose()
            }
            finishActivity()
            return false
        } else {
            super.onKeyDown(keyCode, event)
        }
    }
    override fun transluent(): Boolean {
        return true
    }
    override fun onDestroy() {
        super.onDestroy()
        if (null != disposable) {
            disposable?.dispose()
        }
    }


}
