package com.zxbw.modulemain.box.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.Paint
import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager
import com.umeng.socialize.UMShareAPI
import com.zxbw.modulemain.R
import com.zxbw.modulemain.box.adapter.GoodsPoolAdapter
import com.zxbw.modulemain.box.adapter.TopPagerAdapter
import com.zxbw.modulemain.box.contract.GoodsDetailContract
import com.zxbw.modulemain.box.contract.ProtectionPoolContract
import com.zxbw.modulemain.box.presenter.GoodsDetailPresenter
import com.zxbw.modulemain.box.presenter.ProtectionPoolPresenter
import com.zxbw.modulemain.view.BoxResultDialog
import com.zxbw.modulemain.view.DialogUtils
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.Constant
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.SettingPreference
import com.zxhl.cms.net.model.box.*
import com.zxhl.cms.pay.PayContract
import com.zxhl.cms.utils.*
import com.zxhl.cms.widget.LoadingDialog
import com.zxhl.cms.net.model.uc.PayResultEntity
import com.zxhl.cms.pay.PayDialog
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_layout_new_box_goods_detail.*
import kotlinx.android.synthetic.main.layout_detail_content2.*
import kotlinx.android.synthetic.main.layout_detail_top2.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class NewBoxGoodsDetailActivity : BaseActivity(), GoodsDetailContract.View,
    ProtectionPoolContract.View,
    OnRecycleItemClickListener<HomeBoxListEntity>, AdCallback<String> {
    private var mPresenter: GoodsDetailPresenter? = null
    private var mGoodsPoolPresenter: ProtectionPoolPresenter? = null
    private var mPagerAdapter: TopPagerAdapter? = null//商品展示列表
    private var mPoolAdapter: GoodsPoolAdapter? = 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 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? = ""
    private var duoChouNum = 0;
    private var duoChouPrice: Double = 0.0
    private var newUserPrice: String? = ""
    var activitiesType: Int? = 0
    var activitiesPrice: String? = ""
    var activitiesRefreshId: String? = ""
    var activitiesTimes: Int? = 0
    var newPeople: String? = ""
    var discount: String? = ""
    var boxName: String = ""
    var isShowFive = 1
    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_new_box_goods_detail
    }

    override fun init() {
        //  initPayCoing()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        boxid = intent?.data?.getQueryParameter("boxid") ?: ""

        //返回
        id_detail_img_back?.setOnClickListener {
            this.finish()
        }
        //规则
        id_detail_rule?.setOnClickListener {
            JumpUtils.webJump(
                "规则",
                "https://newspool.zhangxinhulian.com/sspapiNovel/su/custom/xiaoxiangSaveMoney/privacy_app1.html"
            )
        }
        //试玩
        id_detail_shiwan_rl?.setOnClickListener {
//            JumpUtils.lotteryBoxJump(boxid, Constant.Key.TEST_LOTTERY, "")
            BoxResultDialog.showTestLotteryResult(
                this,
                boxid ?: "",
                oneSellCoin,
                fiveSellCoin,
                rePumpingCardNum
            )
        }
        //五连抽
        id_ll_five_lottery?.setOnClickListener {
            BoxResultDialog.setDialogGoodsNum("5")
            EventUtils.onEvent("five_lottery", "5连抽")
//            price = id_tv_five_price?.text.toString()
            price = fiveSellCoin.toString()
            clickType = Constant.Key.FIVE_LOTTERY

            DialogUtils.showBoxSelectDialog(
                this, oneSellCoin, boxName, activitiesType ?: 0
            ) { code, result ->
                if (code == 0) {
                    showToast("请选择想要开启的盒子~")
                } else {

                    BoxResultDialog.showSelectLotteryResult(
                        this@NewBoxGoodsDetailActivity,
                        boxid ?: "",
                        "1",
                        code,
                        result ?: oneSellCoin * code,
                        oneSellCoin,
                        fiveSellCoin,
                        rePumpingCardNum
                    )
                }
            }
        }
        //单抽
        id_ll_one_lottery?.setOnClickListener {
            BoxResultDialog.setDialogGoodsNum("1")
            EventUtils.onEvent("one_lottery", "单抽")
            clickType = Constant.Key.ONE_LOTTERY

            DialogUtils.showBoxSelectDialog(
                this, oneSellCoin, boxName, activitiesType ?: 0
            ) { code, result ->
                if (code == 0) {
                    showToast("请选择想要开启的盒子~")
                } else {
                    BoxResultDialog.showSelectLotteryResult(
                        this@NewBoxGoodsDetailActivity,
                        boxid ?: "",
                        "1",
                        code,
                        result ?: oneSellCoin * code,
                        oneSellCoin,
                        fiveSellCoin,
                        rePumpingCardNum
                    )
                }
            }

        }

        //拥有的币数量
        ownCoin = SettingPreference.getUserCoinNum().toDoubleOrNull()

        mGoodsPoolPresenter = ProtectionPoolPresenter(this)
        //获取商品池列表
        mGoodsPoolPresenter?.getGoods(boxid)
        //
        mPresenter = GoodsDetailPresenter(this)
        //获取盲盒信息
        mPresenter?.getBoxInfo(boxid)
        //道具卡列表
        mPresenter?.getPropsCardList(boxid)
        mPoolAdapter = GoodsPoolAdapter(this)

        //商品池
        id_detail_rl_bottom_pool.layoutManager = LinearLayoutManager(mActivity)
        id_detail_rl_bottom_pool?.adapter = mPoolAdapter
        id_detail_rl_bottom_pool.isNestedScrollingEnabled = false

        playAnimation()

        id_detail_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
                playAnimation()
                id_detail_goods_index.text = "${position + 1}  ${mList?.size ?: 0 + 1}"
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })

        BoxResultDialog.setDialogDismissCallback(object : BoxResultDialog.DialogDismissCallback {
            override fun onDismiss(id: String) {
                boxid = id
                mPresenter?.getPropsCardList(id)
                mPresenter?.getBoxInfo(id)
            }
        })

        floatAnim(id_detail_tv_xuan_fu, 2000)
    }

    //商品显示的动画
    fun playAnimation() {
        id_detail_lottie_daoguang?.visibility = View.VISIBLE
        id_detail_lottie_daoguang?.imageAssetsFolder = "daoguang/images/"
        id_detail_lottie_daoguang?.setAnimation("daoguang/data.json")
        id_detail_lottie_daoguang?.repeatCount = 0
        id_detail_lottie_daoguang?.playAnimation()
        id_detail_lottie_daoguang?.addAnimatorUpdateListener { animation ->
            if (animation?.animatedFraction == 1f) {
                id_detail_lottie_daoguang?.visibility = View.GONE
            }
        }
    }

    //详情信息
    override fun setBoxInfoData(reslut: BoxInfoEntity) {
        //设置商品信息
        newPeople = reslut?.newUserPrice
        newUserPrice = reslut?.newUserPrice
        activitiesPrice = reslut.activitiesPrice
        activitiesTimes = reslut.activitiesTimes
        activitiesType = reslut.activitiesType
        activitiesRefreshId = reslut.activitiesRefreshId
        boxName = reslut.boxName ?: "盲盒"

        if (reslut.activitiesType == 5) {
            Constant.NewUserBox.openDisBoxId = reslut.boxId
            Constant.NewUserBox.tempBoxId = reslut.activitiesRefreshId
            Constant.NewUserBox.tempBoxPrice = reslut.activitiesPrice
            Constant.NewUserBox.tempBoxMainImg = reslut.activitiesRefreshImage
            Constant.NewUserBox.tempBoxMainName = reslut.activitiesRefreshName
        } else {
            Constant.NewUserBox.openDisBoxId = ""
            Constant.NewUserBox.tempBoxId = ""
            Constant.NewUserBox.tempBoxPrice = ""
            Constant.NewUserBox.tempBoxMainImg = ""
            Constant.NewUserBox.tempBoxMainName = ""
        }
        BoxResultDialog.setDialogGoodsInfo(
            reslut?.mainImage ?: "",
            reslut?.boxName ?: "",
            reslut?.originalPrice ?: "",
            "1"
        )
        if (TextUtils.isEmpty(reslut?.discount)) {
            discount = ""
        } else {
            discount = reslut.discount
        }
        if (reslut.activitiesType == 4) {
            if (reslut.activitiesDiscount.isNullOrEmpty()) {
                id_tv_youhui_coin_desc.visibility = View.GONE
            } else {
                id_tv_youhui_coin_desc.visibility = View.VISIBLE
                id_tv_youhui_coin_desc.text = "已优惠${reslut.activitiesDiscount}元"
            }
            if (reslut.originalPrice.isNullOrEmpty()) {
                id_tv_one_original_price.visibility = View.GONE
            } else {
                id_tv_one_original_price.visibility = View.VISIBLE
                id_tv_one_original_price.text = "${reslut.originalPrice}"
                id_tv_one_original_price.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG //中划线
            }
        } else {
            id_tv_one_original_price.visibility = View.GONE
            id_tv_youhui_coin_desc.visibility = View.GONE
        }


        if (reslut.activitiesType == 2) {
            id_ll_five_lottery?.visibility = View.GONE
            id_btn_one_lottery?.text = "买一送一"
            id_tv_oneprice?.text = "￥${reslut.activitiesPrice}"
        } else {
            id_ll_five_lottery?.visibility = View.VISIBLE
            id_btn_one_lottery?.text = "一发入魂"
            id_tv_oneprice?.text = "￥${reslut.onePriceStr}"
        }
        if (TextUtils.isEmpty(newUserPrice)) {
            id_tv_five_price2.text = "￥${reslut.onePrice?.times(5)}"
        } else {
            id_tv_five_price2.text = "￥${newUserPrice?.toDoubleOrNull()?.times(5)}"
        }
        if (boxid.equals("-1") || boxid.equals("-12") || boxid.equals("-11")) {
            newUserPrice = "0"
        }
        //   newUserPrice=reslut?.
        id_tv_good_name?.text = reslut.boxName
        //设置商品价格
        id_tv_price?.text = reslut.onePriceStr
        //设置开盒次数
        id_detail_tv_volume?.text =
            resources.getString(R.string.box_detail_open_box_num, reslut.totalSalesVolume ?: "0")
        isShowFive = reslut.fiveShow ?: 1
        //是否显示五连抽
        if (reslut.fiveShow == 0) {
            id_ll_five_lottery.visibility = View.GONE
        } else {
            id_ll_five_lottery.visibility = View.VISIBLE
        }

        id_tv_five_price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
        id_tv_five_price?.text = "￥${reslut.fivePrice}"

        mList = reslut.goodsList
        fiveSellCoin = reslut?.fivePrice ?: 0.0
        oneSellCoin = reslut?.onePrice ?: 0.0

        Log.e("MXL", "拥有的钱" + ownCoin + "5连价格" + fiveSellCoin + "单次价格" + oneSellCoin)
        if (reslut.activitiesType == 1) {
            id_more_luck_ll_view.visibility = View.VISIBLE
            duoChouNum = reslut.activitiesTimes ?: 0
            duoChouPrice = reslut.activitiesPrice?.toDouble() ?: 0.0
            id_buff_trip2?.text = "限时优惠${reslut.activitiesPrice}元/${reslut.activitiesTimes}个"
            if (reslut.activitiesTimes == 2) {
                id_more_luck_tv.text = "二连\n绝世"
            } else if (reslut.activitiesTimes == 3) {
                id_more_luck_tv.text = "三连\n绝世"
            } else if (reslut.activitiesTimes == 4) {
                id_more_luck_tv.text = "四连\n绝世"
            }
        } else {
            id_more_luck_ll_view.visibility = View.GONE
        }

        if (reslut?.goodsList != null) {
            mPagerAdapter = TopPagerAdapter(reslut?.goodsList!!)
            id_detail_top_viewpager.adapter = mPagerAdapter
        }
        id_detail_goods_index.text = "1  ${mList?.size ?: 0 + 1}"

        if (!TextUtils.isEmpty(reslut?.text)) {
            id_detail_tv_xuan_fu.visibility = View.VISIBLE
            id_detail_tv_xuan_fu?.text = Html.fromHtml("${reslut.text}")
        } else {
            id_detail_tv_xuan_fu.visibility = View.GONE
        }
    }

    @SuppressLint("WrongConstant")
    private fun floatAnim(view: View, delay: Int) {
        val animators: MutableList<Animator> = ArrayList()
        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()
    }


    private var allList: ArrayList<GoodList>? = null

    //商品池的数据
    override fun setData(result: GoodsPoolEntity?) {
        if (allList == null) {
            allList = ArrayList()
        }
        allList?.clear()
        if (result?.list?.l3 != null) {
            allList?.addAll(result?.list?.l3!!)
        }
        if (result?.list?.l2 != null) {
            allList?.addAll(result?.list?.l2!!)
        }
        if (result?.list?.l1 != null) {
            allList?.addAll(result?.list?.l1!!)
        }
        if (result?.list?.l0 != null) {
            allList?.addAll(result?.list?.l0!!)
        }
        mPoolAdapter?.clear()
        mPoolAdapter?.appendToList(allList)
        mPoolAdapter?.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            Log.e("MXL", "onDestroy:EventBus.unregister")
            EventBus.getDefault().unregister(this)
        }
        BoxResultDialog.setDialogDismissCallback(null)
        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_detail_card_chongchou.visibility = View.GONE
            id_detail_card_chongchou_num.visibility = View.GONE

            id_detail_card_shishi.visibility = View.GONE
            id_detail_card_shishi_num.visibility = View.GONE
            id_tv_detail_card_shishi_tips.visibility = View.GONE
        } else {

            if (null == reslut.epicCard) {
                id_detail_card_shishi.visibility = View.GONE
                id_detail_card_shishi_num.visibility = View.GONE
                id_tv_detail_card_shishi_tips.visibility = View.GONE
            } else {
                id_detail_card_shishi.visibility = View.VISIBLE
                id_detail_card_shishi_num.visibility = View.VISIBLE
                id_tv_detail_card_shishi_tips.visibility = View.VISIBLE
            }

            if (reslut.show) {
                id_detail_card_chongchou.visibility = View.VISIBLE
                id_detail_card_chongchou_num.visibility = View.VISIBLE
            } else {
                id_detail_card_chongchou.visibility = View.GONE
                id_detail_card_chongchou_num.visibility = View.GONE
            }
            initPropsCard(reslut)
        }
    }

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


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        PayDialog.onNewIntent(intent)
    }

    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
        PayDialog.OnResumeCheck()
    }


    override fun onResult(code: Int, result: String?) {
        ownCoin = SettingPreference.getUserCoinNum().toDouble()
    }


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


    private var rePumpingCardNum = 0;

    //道具卡
    private fun initPropsCard(result: PropsCardList) {
        //重抽卡
        id_detail_card_chongchou_num.text = "${result.rePumping?.size ?: "0"}"
        rePumpingCardNum = result.rePumping?.size ?: 0
        //重抽卡
        id_detail_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 = ""
                }
            }
            descStr = ""
            useStatus = -1;
            DialogUtils.showPropsCard(this,
                1,
                cardNum,
                useStatus,
                descStr,
                resources.getString(R.string.box_detail_open_box_result_re_pumping_desc2),
                {
                    //left
                }, {
                    //right
                    id_ll_one_lottery.callOnClick()
                })
        }
        if (null != result.epicCard && result.epicCard?.size ?: 0 == 0 && result.epicCardText.isNotEmpty()) {
            id_tv_detail_card_shishi_tips.visibility = View.VISIBLE
            id_tv_detail_card_shishi_tips.text = Html.fromHtml("${result.epicCardText}")
        } else {
            id_tv_detail_card_shishi_tips.visibility = View.GONE
        }
        //史诗卡
        id_detail_card_shishi_num.text = "${result.epicCard?.size ?: "0"}"
        //史诗卡
        id_detail_card_shishi.setOnClickListener {
            EventUtils.onEvent("shishi_card_click")
            var descStr = ""
            var descStr2 = "使用史诗卡开盒,即可随机获得史诗商品"
            var useStatus = 0;
            var cardNum = if (result.epicCard.isNullOrEmpty()) 0 else result.epicCard!!.size;
            if (cardNum == 0) {
                useStatus = -1
                descStr = ""
            } else {
                useStatus = 4
                descStr = "确定使用史诗卡吗？"
            }
            DialogUtils.showPropsCard(this,
                4,
                cardNum,
                useStatus,
                descStr, descStr2,
                {
                    //left
                }, {
                    //right
                    if (useStatus == 4) {
                        BoxResultDialog.showEpicCardLotteryResult(
                            this,
                            boxid ?: "",
                            oneSellCoin,
                            fiveSellCoin
                        )
                    }
                })
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(payEvent: PayEvent) {
        Log.e("MXL", "goodsDetail充值回传" + payEvent.onePrice + payEvent.boxId)
        if (TextUtils.equals(payEvent.page, "1")) {
            if (TextUtils.equals(payEvent.type, Constant.Key.ONE_LOTTERY)) {
                BoxResultDialog.showOneLotteryResult(
                    this,
                    payEvent.boxId ?: "",
                    payEvent.onePrice!!,
                    payEvent.fivePrice!!,
                    payEvent.newUserPrice,
                    "1",
                    rePumpingCardNum, isShowFive
                )
            } else if (TextUtils.equals(payEvent.type, Constant.Key.FIVE_LOTTERY)) {
                BoxResultDialog.showFiveLotteryResult(
                    this,
                    payEvent.boxId ?: "",
                    payEvent.onePrice!!,
                    payEvent.fivePrice!!,
                    rePumpingCardNum
                )
            } else if (TextUtils.equals(payEvent.type, Constant.Key.SURPRISE_LOTTERY)) {
                BoxResultDialog.showSurpriseLotteryResult(
                    this,
                    boxid ?: "",
                    oneSellCoin,
                    fiveSellCoin,
                    activitiesPrice?.toDoubleOrNull()!!,
                    discount.toString(),
                    activitiesTimes!!,
                    activitiesRefreshId.toString(),
                    "1"
                )
            } else if (TextUtils.equals(payEvent.type, Constant.Key.EPIC_CARD_LOTTERY)) {
                BoxResultDialog.showEpicCardLotteryResult(
                    this,
                    boxid ?: "",
                    oneSellCoin,
                    fiveSellCoin
                )
            } else if (TextUtils.equals(payEvent.type, Constant.Key.SELECT_LOTTERY)) {
                BoxResultDialog.showSelectLotteryResult(
                    this,
                    payEvent.boxId ?: "",
                    "1",
                    payEvent.selectNum ?: 0,
                    payEvent.selectPrice ?: 0.0,
                    oneSellCoin,
                    fiveSellCoin,
                    rePumpingCardNum
                )
            }

        }

    }

}