package com.zxhl.main.page.activity

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.NetConfig
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.*
import com.zxhl.cms.net.model.video.MemberEntity
import com.zxhl.cms.pay.PayActivity
import com.zxhl.cms.pay.PayContract
import com.zxhl.cms.pay.PayPresenter
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.main.R
import com.zxhl.main.page.adapter.AutoPollAdapter
import com.zxhl.main.page.adapter.BoxAdapter
import com.zxhl.main.page.adapter.DetailMiddleAdapter
import com.zxhl.main.page.adapter.TopPagerAdapter
import com.zxhl.main.page.contract.GoodsDetailContract
import com.zxhl.main.page.presenter.GoodsDetailPresenter
import com.zxhl.main.page.view.DialogUtils
import com.zxhl.main.page.view.ProtectionPoolPopupWindow
import com.zxhl.novel.utils.server.PayResultEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_layout_goods_detail.*
import kotlinx.android.synthetic.main.layout_detail_content.*
import kotlinx.android.synthetic.main.layout_detail_title.*
import kotlinx.android.synthetic.main.layout_detail_title.id_img_back
import kotlinx.android.synthetic.main.layout_detail_top.*


class GoodsDetailActivity : BaseActivity(), GoodsDetailContract.View,
    OnRecycleItemClickListener<HomeBoxListEntity>, WeChatLoginSuccessCallBall, AdCallback<String>,
    PayContract.View {
    private var mPresenter: GoodsDetailPresenter? = null
    private var mPagerAdapter: TopPagerAdapter? = null
    private var mAdapter: BoxAdapter? = null
    private var mList: List<GoodList>? = null
    private var p: Int = 0
    private var needPrice: String? = ""
    private var ownCoin: Double? = 0.0
    private var oneSellCoin: Double? = 0.0
    private var fiveSellCoin: Double? = 0.0
    private var boxid: String? = ""
    private var wechatutil: WeChatUtils? = null
    private var mListImgView: MutableList<ImageView> = ArrayList()
    private var mSwitchMainObservable: Observable<Int>? = null
    private var price: String? = ""
    private var mPayPresenter: PayContract.Presenter? = null
    private var mLoading: LoadingDialog? = null
    private var payResultObservable: Observable<PayResultEntity>? = null
    private var pay_type = 0
    private var clickType: String? = ""
    override fun onClick(v: View?) {

    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.transparent))
    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_goods_detail
    }

    override fun init() {
        initPayCoing()
        boxid = intent?.data?.getQueryParameter("boxid") ?: ""
        mListImgView?.add(id_img1)
        mListImgView?.add(id_img2)
        mListImgView?.add(id_img3)
        mListImgView?.add(id_img4)
        mListImgView?.add(id_img5)
        wechatutil = WeChatUtils(this, this)
        id_img_back?.setOnClickListener {
            this.finish()
        }
        id_tv_kefu?.setOnClickListener {
            //跳转客服页
            JumpUtils.webJump("客服", NetConfig.H5.WEB_URL_CUSTOMER_SERVICE)
        }
        id_img_kaihe?.setOnClickListener {
            //开盒
            JumpUtils.lotteryBoxJump(boxid, Constant.Key.TEST_LOTTERY, price)
        }
        id_img_shiwan.visibility = View.GONE
        id_img_shiwan2?.setOnClickListener {
            //试玩
            JumpUtils.lotteryBoxJump(boxid, Constant.Key.TEST_LOTTERY, "")
        }
        id_tv_baodi?.setOnClickListener {
            ProtectionPoolPopupWindow().init(this, boxid)
        }
        id_ll_five_chou?.setOnClickListener {
            EventUtils.onEvent("five_lottery", "5连抽")
            EventUtils.onEvent("five_lottery_boxid", "" + boxid)
            price = id_tv_five_price?.text.toString()
            clickType = Constant.Key.FIVE_LOTTERY
            if (ownCoin?.compareTo(fiveSellCoin!!)!! >= 0) {
                JumpUtils.lotteryBoxJump(boxid, Constant.Key.FIVE_LOTTERY, price)
//                if (wechatutil!!.isWechatLogin() == true) {
//                    JumpUtils.lotteryBoxJump(boxid, Constant.Key.FIVE_LOTTERY, price)
//                } else {
//                    JumpUtils.ThirdPardLoginJump()
//                  //  wechatutil!!.wechatLogin(this, Constant.Key.FIVE_LOTTERY)
//                }
                //  JumpUtils.lotteryBoxJump(boxid, Constant.Key.FIVE_LOTTERY)
            } else {
                needPrice = id_tv_five_price.text.toString()
                if (ownCoin != null) {
                    val chajia = needPrice?.toDoubleOrNull()?.minus(ownCoin!!)
                    if (TextUtils.equals("flow_tag_xymh_z", SettingPreference.getFlowTag())) {
                        mLoading?.setLoading("loading")
                        mLoading?.show()
                        if (pay_type == 1) {
                            mPayPresenter?.requestAliPay(
                                this,
                                chajia.toString(),
                                pay_type.toString(),
                                "6"
                            )
                        } else {
                            mPayPresenter?.requestMiniProgrom(
                                chajia.toString(),
                                pay_type.toString(),
                                "6"
                            )
                        }
                    } else {
                        JumpUtils.payJump(boxid, chajia.toString(), Constant.Key.FIVE_LOTTERY)
                    }

                }
            }

        }
        id_ll_one_chou?.setOnClickListener {
            EventUtils.onEvent("one_lottery", "单抽")
            EventUtils.onEvent("one_lottery_boxid", "" + boxid)
            clickType = Constant.Key.ONE_LOTTERY
            price = id_tv_oneprice?.text.toString()
            Log.e("MXL", "sss" + ownCoin?.compareTo(oneSellCoin!!))
            if (ownCoin?.compareTo(oneSellCoin!!)!! >= 0) {
                JumpUtils.lotteryBoxJump(boxid, Constant.Key.ONE_LOTTERY, price)
//                if (wechatutil!!.isWechatLogin() == true) {
//
//                    JumpUtils.lotteryBoxJump(boxid, Constant.Key.ONE_LOTTERY, price)
//                } else {
//                    Log.e("MXL", "未登录")
////                    onWxLogin()
//                    JumpUtils.ThirdPardLoginJump()
//                   // wechatutil!!.wechatLogin(this, Constant.Key.ONE_LOTTERY)
//                }
                //  JumpUtils.lotteryBoxJump(boxid, Constant.Key.ONE_LOTTERY)
            } else {
                needPrice = id_tv_oneprice.text.toString()
                if (ownCoin != null) {
                    val chajia = needPrice?.toDoubleOrNull()?.minus(ownCoin!!)
                    if (TextUtils.equals("flow_tag_xymh_z", SettingPreference.getFlowTag())) {
                        mLoading?.setLoading("loading")
                        mLoading?.show()
                        if (pay_type == 1) {
                            mPayPresenter?.requestAliPay(
                                this,
                                chajia.toString(),
                                pay_type.toString(),
                                "6"
                            )
                        } else {
                            mPayPresenter?.requestMiniProgrom(
                                chajia.toString(),
                                pay_type.toString(),
                                "6"
                            )
                        }
                    } else {
                        JumpUtils.payJump(boxid, chajia.toString(), Constant.Key.ONE_LOTTERY)
                    }
                }

            }
        }
        id_tv_detail_coin?.setOnClickListener {
            JumpUtils.payJump("0", "0", "0")
        }
        id_tv_detail_coin?.text = SettingPreference.getUserCoinNum()
        ownCoin = SettingPreference.getUserCoinNum().toDoubleOrNull()
        mPresenter = GoodsDetailPresenter(this)
        mPresenter?.getBoxInfo(boxid)
        mPresenter?.getBoxMarquee(boxid)
        mPresenter?.getPropsCardList(boxid)
        mAdapter = BoxAdapter(mActivity, this)
        id_rl_bottom.layoutManager = LinearLayoutManager(mActivity)
        id_rl_bottom?.adapter = mAdapter
        id_rl_bottom.setNestedScrollingEnabled(false)
//        val animation: Animation = AnimationUtils.loadAnimation(this, R.anim.view_animation)
//        id_tv_xuan_fu?.animation=animation
        floatAnim(id_tv_xuan_fu, 2000)
        playAnimation()
        id_top_viewpager?.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                Log.e("MXL", "" + position)
                p = position
                setGoodsInfo(position)
                playAnimation()
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })
        mSwitchMainObservable = RxBus.get().register(Constant.SWITCH_PAGE, Int::class.java)
        mSwitchMainObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe({ s -> finish() }) {

            }

    }

    @SuppressLint("WrongConstant")
    private fun floatAnim(view: View, delay: Int) {
        val animators: MutableList<Animator> = ArrayList()
//        val translationXAnim = ObjectAnimator.ofFloat(view, "translationX", 0f, 0f, 0f)
//        translationXAnim.duration = 0
//        translationXAnim.repeatCount = ValueAnimator.INFINITE //无限循环
//        translationXAnim.repeatMode = ValueAnimator.INFINITE //
//        translationXAnim.start()
//        animators.add(translationXAnim)
        val translationYAnim = ObjectAnimator.ofFloat(view, "translationY", -8f, 10f, -8f)
        translationYAnim.duration = 3000
        translationYAnim.repeatCount = ValueAnimator.INFINITE
        translationYAnim.repeatMode = ValueAnimator.INFINITE
        translationYAnim.start()
        animators.add(translationYAnim)
        val btnSexAnimatorSet = AnimatorSet()
        btnSexAnimatorSet.playTogether(animators)
        btnSexAnimatorSet.startDelay = delay.toLong()
        btnSexAnimatorSet.start()
    }

    fun playAnimation() {
        id_lottie_daoguang?.visibility = View.VISIBLE
        id_lottie_daoguang?.imageAssetsFolder = "daoguang/images/"
        id_lottie_daoguang?.setAnimation("daoguang/data.json")
        id_lottie_daoguang?.repeatCount = 0
        id_lottie_daoguang?.playAnimation()
        id_lottie_daoguang?.addAnimatorUpdateListener(object :
            ValueAnimator.AnimatorUpdateListener {
            override fun onAnimationUpdate(animation: ValueAnimator?) {
                if (animation?.animatedFraction == 1f) {
                    id_lottie_daoguang?.visibility = View.GONE
                }
            }
        })
    }

    override fun setBoxInfoData(reslut: BoxInfoEntity) {
        if (reslut.fiveShow == 0) {
            id_ll_five_chou.visibility = View.GONE
        } else {
            id_ll_five_chou.visibility = View.VISIBLE
        }
        mList = reslut.goodsList
        fiveSellCoin = reslut?.fivePrice
        oneSellCoin = reslut?.onePrice?.toDouble()
        Log.e("MXL", "拥有的钱" + ownCoin + "5连价格" + fiveSellCoin + "单次价格" + oneSellCoin)
        id_buff_trip?.text = "获得普通款可提高buff"
        id_tv_volume?.text = "已开袋${reslut.totalSalesVolume ?: "0"}次"
        id_tv_five_price?.text = "${reslut.fivePrice}"
        if (!TextUtils.isEmpty(reslut?.text)) {
            id_tv_xuan_fu.visibility = View.VISIBLE
            id_tv_xuan_fu?.text = Html.fromHtml("${reslut.text}")
        } else {
            id_tv_xuan_fu.visibility = View.GONE
        }

        id_tv_five_price2?.text = "${reslut.onePrice?.times(5)}"
        setMiddleAuto()
        mAdapter?.clear()
        mAdapter?.appendToList(reslut?.otherList)
        mAdapter?.notifyDataSetChanged()
        id_tv_five_price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
        id_tv_oneprice?.text = "${reslut.onePriceStr}"
        for (i in 0 until (reslut?.headImages?.size ?: 0)) {
            if (i < mListImgView.size) {
                Glide.with(this).load(reslut?.headImages!![i])
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .into(mListImgView[i])
            }

        }
        setGoodsInfo(p)
        if (reslut?.goodsList != null) {
            mPagerAdapter = TopPagerAdapter(reslut?.goodsList!!)
            id_top_viewpager.adapter = mPagerAdapter
        }

    }

    override fun onDestroy() {
        super.onDestroy()

        if (mSwitchMainObservable != null) {
            RxBus.get().unregister(Constant.SWITCH_PAGE, mSwitchMainObservable!!)
        }
        if (payResultObservable != null)
            RxBus.get().unregister(Constant.PAY_RESULT, payResultObservable!!)
    }

    override fun setMarqueeData(reslut: List<MarqueeEntity>?) {
        id_auto_rl?.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        id_auto_rl?.adapter = AutoPollAdapter(this, reslut)
        id_auto_rl?.start()
    }

    override fun setPropsCardList(reslut: PropsCardList?) {
        if (null == reslut) {
            id_ll_props_card_view.visibility = View.GONE
        } else {
            if (reslut.show) {
                id_ll_props_card_view.visibility = View.VISIBLE
                initPropsCard(reslut)
            } else {
                id_ll_props_card_view.visibility = View.GONE
            }
        }
    }


    fun setMiddleAuto() {
        id_rl_middle?.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        id_rl_middle?.adapter = DetailMiddleAdapter(this, mList)
        id_rl_middle?.start()
    }

    fun setGoodsInfo(p: Int) {
        id_tv_good_name?.text = mList?.get(p)?.productName
        id_tv_price?.text = mList?.get(p)?.salePriceStr
        id_tv_cate_name?.text = mList?.get(p)?.cateName
        if (mList?.get(p)?.goodsLevel.equals("0")) {
            //普通
            id_tv_cate_name?.setBackgroundResource(R.drawable.shape_putong_bg)
        } else if (mList?.get(p)?.goodsLevel.equals("1")) {
            //稀有
            id_tv_cate_name?.setBackgroundResource(R.drawable.shape_xiyou_bg)
        } else if (mList?.get(p)?.goodsLevel.equals("2")) {
            //史诗
            id_tv_cate_name?.setBackgroundResource(R.drawable.shape_shishi_bg)
        } else if (mList?.get(p)?.goodsLevel.equals("3")) {
            //传说
            id_tv_cate_name?.setBackgroundResource(R.drawable.shape_chuanshuo_bg)
        }
    }

    override fun onItemClick(view: View?, position: Int, data: HomeBoxListEntity?) {
        JumpUtils.goodsDetailJump(data?.boxId)
    }

    override fun loginSuccess(lotteryStr: String?) {
        Log.e("MXl", "登录回调" + lotteryStr)
        JumpUtils.lotteryBoxJump(boxid, lotteryStr, price)

    }

    private var isPause = false

    override fun onPause() {
        super.onPause()
        isPause = true

    }

    override fun onResume() {
        super.onResume()
        if (isPause) {
            UserDataUtils.updateUserInfo(this)
            mPresenter?.getBoxInfo(boxid)
            mPresenter?.getPropsCardList(boxid)
        }
        isPause = false
    }


    override fun onResult(code: Int, result: String?) {
        Log.e("MXL", "更新详情页用户余额")
        id_tv_detail_coin?.text = SettingPreference.getUserCoinNum()
        ownCoin = SettingPreference.getUserCoinNum().toDouble()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
        } catch (ex: Exception) {
        }
    }

    fun initPayCoing() {
        mLoading = LoadingDialog.getLoadingDialog(
            this,
            getString(com.zxhl.cms.R.string.wait_ing),
            false,
            false
        )
        mPayPresenter = PayPresenter(this)
        mPayPresenter?.appInfo()
        payResultObservable = RxBus.get().register(Constant.PAY_RESULT, PayResultEntity::class.java)
        payResultObservable?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(Consumer<PayResultEntity> { obj ->
                if (obj.isPaySuc) {
                    EventUtils.onEvent("pay_page_pay_query_order", "付款成功")
                    mPayPresenter?.verifyPay(obj.txt, obj.payType)
                } else {
                    showResultLoading(false)
                }
            }, Consumer<Throwable> { })
    }

    private fun showResultLoading(isPaySuc: Boolean) {
        if (isPaySuc) {
            EventUtils.onEvent("pay_suc")
            mLoading?.setResult(true, "支付成功", 1000)
        } else {
            EventUtils.onEvent("pay_fail")
            mLoading?.setResult(false, "支付失败", 1000)
        }

    }

    override fun updatePriceList(data: List<MemberEntity.ProductDetail>) {

    }

    override fun verifyOrderFail() {
        showResultLoading(false)
    }

    override fun requestOrderSuc() {
        mLoading?.setLoading("正在支付")
    }

    override fun verifyOrderSuc(orsder: String) {
        UserDataUtils.updateUserInfo(this)
        showResultLoading(true)
        JumpUtils.lotteryBoxJump(boxid, clickType, price)
    }

    override fun setCanInvest(boolean: Boolean?) {

    }

    override fun setOrderNo(order: String?) {

    }

    override fun setAppInfo(result: AppInEntity?) {
        if (result != null) {

            if (result.pay_ali.equals("1") && result.pay_wx.equals("0")) {
                pay_type = PayActivity.ALI_PAY
            } else {
                pay_type = PayActivity.MINI_PROGRAM
            }


        }
    }


    //道具卡
    private fun initPropsCard(result: PropsCardList) {
        //暴击卡
        if (!result.criticalHit.isNullOrEmpty()) {
            id_card_baoji_num.text = " x${result.criticalHit?.size} "
            id_card_baoji_num.setTextColor(Color.parseColor("#4C84FF"))
            id_card_baoji_num.textSize = 12f
            id_card_baoji_suo.visibility = View.GONE
        } else {
            id_card_baoji_num.text = "未获得"
            id_card_baoji_num.setTextColor(Color.parseColor("#999999"))
            id_card_baoji_num.textSize = 10f
            id_card_baoji_suo.visibility = View.VISIBLE
        }
        //重抽卡
        if (!result.rePumping.isNullOrEmpty()) {
            id_card_chongchou_num.text = " x${result.rePumping?.size} "
            id_card_chongchou_num.setTextColor(Color.parseColor("#4C84FF"))
            id_card_chongchou_num.textSize = 12f
            id_card_chongchou_suo.visibility = View.GONE

        } else {
            id_card_chongchou_num.text = "未获得"
            id_card_chongchou_num.setTextColor(Color.parseColor("#999999"))
            id_card_chongchou_num.textSize = 10f
            id_card_chongchou_suo.visibility = View.VISIBLE

        }
        //回血卡
        if (!result.bloodReturn.isNullOrEmpty()) {
            id_card_huixue_num.text = " x${result.bloodReturn?.size} "
            id_card_huixue_num.setTextColor(Color.parseColor("#4C84FF"))
            id_card_huixue_num.textSize = 12f
            id_card_huixue_suo.visibility = View.GONE

        } else {
            id_card_huixue_num.text = "未获得"
            id_card_huixue_num.setTextColor(Color.parseColor("#999999"))
            id_card_huixue_num.textSize = 10f
            id_card_huixue_suo.visibility = View.VISIBLE
        }

        //暴击卡
//        id_card_baoji.setOnClickListener {
//            EventUtils.onEvent("baoji_card_click")
//            var descStr = ""
//            if (result.criticalHitNum == 1) {
//                descStr = "下次抽取,即可获得暴击卡"
//            } else {
//                descStr = "再抽${result.criticalHitNum}次即可获得暴击卡";
//            }
//            DialogUtils.showPropsCard(this,
//                2, if (result.criticalHit.isNullOrEmpty()) 0 else result.criticalHit!!.size, 0,
//                descStr,
//                "使用暴击卡可多获得一件商品",
//                {
//                    //left
//                }, {
//                    //right
//                    id_ll_one_chou.callOnClick()
//                })
//        }
        //重抽卡
        id_card_chongchou.setOnClickListener {
            EventUtils.onEvent("chongchou_click")
            var descStr = ""
            var useStatus = 0;
            var cardNum = if (result.rePumping.isNullOrEmpty()) 0 else result.rePumping!!.size;
            if (result.rePumpingNum == 1) {
                descStr = "下次必得重抽卡"
            } else {
                descStr = "再抽${result.rePumpingNum}次即可获得重抽卡";
                if (result.rePumpingNum == -1){
                    descStr = ""
                }
            }

            if (cardNum<=0&&result.rePumpingNum == -1){
                descStr = ""
                useStatus = -1;
            }

            DialogUtils.showPropsCard(this,
                1,
                cardNum,
                useStatus,
                descStr,
                "Not satisfied with the product, you can use the reopen card to reopen the box for free",
                {
                    //left
                }, {
                    //right
                    id_ll_one_chou.callOnClick()
                })
        }
        //回血卡
//        id_card_huixue.setOnClickListener {
//            EventUtils.onEvent("huixue_card_click")
//            var descStr = ""
//            if (result.bloodReturnNum == 1) {
//                descStr = "下次抽取,即可获得回血卡"
//            } else {
//                descStr = "再抽${result.bloodReturnNum}次即可获得回血卡";
//            }
//            DialogUtils.showPropsCard(this,
//                3, if (result.bloodReturn.isNullOrEmpty()) 0 else result.bloodReturn!!.size, 0,
//                descStr,
//                "使用回血卡可提升回收获得的幸运币",
//                {
//                    //left
//                }, {
//                    //right
//                    id_ll_one_chou.callOnClick()
//                })
//        }
    }


}