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.Paint
import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager
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.GoodsPoolAdapter
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.BoxResultDialog
import com.zxhl.main.page.view.DialogUtils
import com.zxhl.main.page.view.ProtectionPoolContract
import com.zxhl.main.page.view.ProtectionPoolPresenter
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_new_box_goods_detail.*
import kotlinx.android.synthetic.main.layout_detail_content2.*
import kotlinx.android.synthetic.main.layout_detail_top2.*


class NewBoxGoodsDetailActivity : BaseActivity(), GoodsDetailContract.View,
    ProtectionPoolContract.View,
    OnRecycleItemClickListener<HomeBoxListEntity>, WeChatLoginSuccessCallBall, AdCallback<String>,
    PayContract.View {
    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 wechatutil: WeChatUtils? = null
    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_new_box_goods_detail
    }

    override fun init() {
        initPayCoing()
        boxid = intent?.data?.getQueryParameter("boxid") ?: ""

        wechatutil = WeChatUtils(this, this)
        wechatutil?.isWechatLogin(null)
        //返回
        id_detail_img_back?.setOnClickListener {
            this.finish()
        }
        //规则
        id_detail_rule?.setOnClickListener {
            JumpUtils.webJump("Rule",NetConfig.H5.WEB_URL_RULE)
        }
        //试玩
        id_detail_shiwan_rl?.setOnClickListener {
            if (!Constant.Switch.isLogin){
                JumpUtils.ThirdPardLoginJump()
                return@setOnClickListener
            }
//            JumpUtils.lotteryBoxJump(boxid, Constant.Key.TEST_LOTTERY, "")
            BoxResultDialog.showTestLotteryResult(
                this,
                boxid ?: "",
                oneSellCoin,
                fiveSellCoin,
                rePumpingCardNum
            )
        }
        //五连抽
        id_btn_five_lottery?.setOnClickListener {
            if (!Constant.Switch.isLogin){
                JumpUtils.ThirdPardLoginJump()
                return@setOnClickListener
            }
            EventUtils.onEvent("five_lottery", "5连抽")
            EventUtils.onEvent("five_lottery_boxid", "" + boxid)
//            price = id_tv_five_price?.text.toString()
            price = fiveSellCoin.toString()
            clickType = Constant.Key.FIVE_LOTTERY
            //拥有的币足够
            if (ownCoin?.compareTo(fiveSellCoin!!)!! >= 0) {
                BoxResultDialog.showFiveLotteryResult(
                    this,
                    boxid ?: "",
                    oneSellCoin,
                    fiveSellCoin
                )
            } else {
                needPrice = fiveSellCoin.toString()
                JumpUtils.payJump(boxid, needPrice, Constant.Key.FIVE_LOTTERY)
            }

        }
        //单抽
        id_btn_one_lottery?.setOnClickListener {
            if (!Constant.Switch.isLogin){
                JumpUtils.ThirdPardLoginJump()
                return@setOnClickListener
            }
            EventUtils.onEvent("one_lottery", "单抽")
            EventUtils.onEvent("one_lottery_boxid", "" + boxid)
            clickType = Constant.Key.ONE_LOTTERY
            price = oneSellCoin.toString()
            Log.e("MXL", "sss" + ownCoin?.compareTo(oneSellCoin!!))
            if (ownCoin?.compareTo(oneSellCoin!!)!! >= 0) {
                BoxResultDialog.showOneLotteryResult(
                    this,
                    boxid ?: "",
                    oneSellCoin,
                    fiveSellCoin, rePumpingCardNum
                )
            } else {
                needPrice = oneSellCoin.toString()
                JumpUtils.payJump(boxid, needPrice, Constant.Key.ONE_LOTTERY)
            }
        }
        //拥有的币数量
        ownCoin = SettingPreference.getUserCoinNum().toDoubleOrNull()

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

        //商品池
        id_detail_rl_bottom_pool.layoutManager = GridLayoutManager(mActivity, 2)
        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) {

            }

        })

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

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

            override fun onLotterySuccess() {
                mPresenter?.getBoxInfo(boxid)
            }
        })

        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) {
        //设置商品信息
        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")
        //是否显示五连抽
        if (reslut.fiveShow == 0) {
            id_btn_five_lottery.visibility = View.GONE
        } else {
            id_btn_five_lottery.visibility = View.VISIBLE
        }
        mList = reslut.goodsList
        fiveSellCoin = reslut?.fivePrice ?: 0.0
        oneSellCoin = reslut?.onePrice ?: 0.0
        Log.e("MXL", "拥有的钱" + ownCoin + "5连价格" + fiveSellCoin + "单次价格" + oneSellCoin)
        id_tv_one_lottery_price?.text = "${reslut.onePriceStr}"
        id_tv_five_lottery_price?.text = "${reslut.fivePrice}"
        id_tv_five_lottery_price2?.text = "${reslut.onePrice?.times(5)}"
        id_tv_five_lottery_price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG) //中划线
        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
        }
        BoxResultDialog.setDialogPrice(oneSellCoin,fiveSellCoin)
    }

    @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?.l0 != null) {
            allList?.addAll(result?.list?.l3!!)
        }
        if (result?.list?.l1 != null) {
            allList?.addAll(result?.list?.l2!!)
        }
        if (result?.list?.l2 != null) {
            allList?.addAll(result?.list?.l1!!)
        }
        if (result?.list?.l3 != null) {
            allList?.addAll(result?.list?.l0!!)
        }
        mPoolAdapter?.clear()
        mPoolAdapter?.appendToList(allList)
        mPoolAdapter?.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        BoxResultDialog.setDialogDismissCallback(null)
        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_detail_card_chongchou.visibility = View.GONE
            id_detail_card_chongchou_num.visibility = View.GONE
        } else {
            if (reslut.show) {
                id_detail_card_chongchou.visibility = View.VISIBLE
                id_detail_card_chongchou_num.visibility = View.VISIBLE
                initPropsCard(reslut)
            } else {
                id_detail_card_chongchou.visibility = View.GONE
                id_detail_card_chongchou_num.visibility = View.GONE
            }
        }
    }

    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)
        if (lotteryStr == Constant.Key.ONE_LOTTERY) {
            BoxResultDialog.showOneLotteryResult(
                this,
                boxid ?: "",
                oneSellCoin,
                fiveSellCoin,
                rePumpingCardNum
            )
        } else if (lotteryStr == Constant.Key.FIVE_LOTTERY) {
            BoxResultDialog.showFiveLotteryResult(
                this,
                boxid ?: "",
                oneSellCoin,
                fiveSellCoin,
                rePumpingCardNum
            )
        } else if (lotteryStr == Constant.Key.TEST_LOTTERY) {
            BoxResultDialog.showTestLotteryResult(
                this,
                boxid ?: "",
                oneSellCoin,
                fiveSellCoin,
                rePumpingCardNum
            )
        }
    }

    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", "更新详情页用户余额")
        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)
        if (clickType == Constant.Key.ONE_LOTTERY) {
            BoxResultDialog.showOneLotteryResult(this, boxid ?: "", oneSellCoin, fiveSellCoin)
        } else if (clickType == Constant.Key.FIVE_LOTTERY) {
            BoxResultDialog.showFiveLotteryResult(this, boxid ?: "", oneSellCoin, fiveSellCoin)
        }
    }

    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 var rePumpingCardNum = 0;

    //道具卡
    private fun initPropsCard(result: PropsCardList) {
        //重抽卡
        id_detail_card_chongchou_num.text = "${result.rePumping?.size}"
        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 = ""
                }
            }

//            if (cardNum <= 0 && result.rePumpingNum == -1) {
//                descStr = ""
//                useStatus = -1;
//            }
            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_btn_one_lottery.callOnClick()
                })
        }

    }


}