package com.duben.microtribe.ui.fragment

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import android.widget.FrameLayout
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.duben.microtribe.R
import com.duben.microtribe.ad.AdManager
import com.duben.microtribe.ad.AdStatusListener
import com.duben.microtribe.ad.NoPreAdManager
import com.duben.microtribe.ad.express.ExpressAdCallback
import com.duben.microtribe.ad.express.MyExpressManager
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.common.Constant
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.mvp.model.NineListBean
import com.duben.microtribe.mvp.model.NineShowBean
import com.duben.microtribe.mvp.model.UserBean
import com.duben.microtribe.mvp.presenters.MyPresenter
import com.duben.microtribe.mvp.views.MyView
import com.duben.microtribe.ui.activitys.*
import com.duben.microtribe.ui.fragment.base.LazyLoadBaseFragment
import com.duben.microtribe.ui.widgets.DialogListener
import com.duben.microtribe.ui.widgets.NineContinueDialog
import com.duben.microtribe.utils.AppPreferencesManager
import com.duben.microtribe.utils.SpanUtils
import com.duben.microtribe.utils.TimeRender
import com.duben.microtribe.utils.UIUtils
import com.duben.microtribe.utils.rxutil.CommonRxTask
import com.duben.microtribe.utils.rxutil.RxjavaUtil
import com.duben.library.utils.nodoubleclick.AntiShake
import kotlinx.android.synthetic.main.fragment_main_my.*

/**
 * 描述：我
 * 作者：孟崔广
 * 时间：2023/7/7 11:30
 */
class MyFragment : LazyLoadBaseFragment(), MyView, View.OnClickListener {

    private val myPresenter by lazy { MyPresenter() }
    private val userManager by lazy { UserManager.getInstance() }

    val luckyIndexMap: MutableMap<Int, String> = HashMap()
    private var yoyo: YoYo.YoYoString? = null
    private var isInitLuckyData = false
    private var isTurnLuckyPage = false
    private var nineShowBean: NineShowBean? = null
    var carrierType = Constant.CARRIERTYPE_NINE

    override fun getContentViewLayoutID() = R.layout.fragment_main_my

    override fun initViewsAndEvents() {
        myPresenter.attachView(this)

        tv_contact.text = SpanUtils()
            .append("如有问题，请直接联系")
            .append("在线客服\n")
            .setForegroundColor(resources.getColor(R.color.main_mints))
            .append("处理速度更快，")
            .append("无需联系支付宝")
            .setForegroundColor(resources.getColor(R.color.main_mints))
            .create()

        initListener()
    }

    override fun onFragmentFirstVisible() {
        super.onFragmentFirstVisible()

    }


    override fun onDestroy() {
        super.onDestroy()
        yoyo?.stop()
        yoyo = null
        myPresenter.detachView()
    }

    override fun onFragmentResume() {
        super.onFragmentResume()

        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_FOUR) {
            if (AntiShake.check(ll_my_record?.id)) return

            if(userManager.vipFlag){
                MyExpressManager.instance.preLoadAd()
                showAd()
            }

            if(isTurnLuckyPage){
                isTurnLuckyPage=false
                clickTurn()
            }

            if (!TextUtils.isEmpty(userManager?.userID)) {
//                myPresenter.showTurn()
                myPresenter.getMyInfo()
            } else {
                myPresenter.userLogin()
            }
        }
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.tv_my_btn -> {
                if (!userManager.vipFlag) {
                    readyGo(VipActivity::class.java)
                }
            }
            R.id.ll_my_setting -> {
                readyGo(SettingsActivity::class.java)
            }
            R.id.tv_my_account, R.id.ll_my_login -> {
                if (!userManager.userIsLogin()) {
                    readyGo(MobileLoginActivity::class.java)
                }
            }
            R.id.ll_my_record -> {
                readyGo(WatchRecordActivity::class.java)
            }
            R.id.ll_my_feed -> {
                readyGo(FeedbackActivity::class.java)
            }
            R.id.ll_contactus -> {
                (requireActivity() as MainActivity).backPhoneDialog()
            }
            R.id.ll_my_payrecord -> {
                readyGo(OrderRecordActivity::class.java)
            }
            R.id.btn_action,R.id.rl_lucky -> {
                clickTurn()
            }
        }
    }

    override fun getUserSuc(data: UserBean) {
        loginStatus(data)
    }

    private fun loginStatus(consumer: UserBean) {
        // 1-匹配用户
        if (consumer.activiteFlag == 1) {
            // 匹配
            ll_my_vip.visibility = View.VISIBLE
            ll_my_payrecord.visibility = View.VISIBLE
            ll_contactus.visibility = View.VISIBLE
            line_my_payrecord.visibility = View.VISIBLE
            line_my_contactus.visibility = View.VISIBLE
        } else {
            // 未匹配
            ll_my_vip.visibility = View.GONE
            ll_my_payrecord.visibility = View.GONE
            ll_contactus.visibility = View.GONE
            line_my_payrecord.visibility = View.GONE
            line_my_contactus.visibility = View.GONE
        }

        // 2-是否有手机号
        if (!TextUtils.isEmpty(userManager.mobile)) {
            tv_my_account.text = "手机号:" + consumer.mobile.substring(0,3)+"****"+consumer.mobile.substring(consumer.mobile.length-4)
            iv_my_bind.visibility = View.GONE
        } else {
            tv_my_account.text = "绑定手机号"
            iv_my_bind.visibility = View.VISIBLE
        }
        tv_my_id.text = "用户ID:"+consumer.idcode

        // 3-vip
        if (consumer.expireTime > 0) {
            tv_my_vip.text = "VIP会员"
            tv_my_btn.visibility = View.GONE
            if (consumer.isForever) {
                tv_my_status.text = "有效期: 永久有效"
            } else {
                tv_my_status.text =
                    "到期时间 ${TimeRender.formatDate(consumer.expireTime, TimeRender.DEFAULT_FORMAT)}"
            }
        } else {
            tv_my_vip.text = "开通VIP会员"
            tv_my_status.text = "解锁全部短剧"
            tv_my_btn.visibility = View.VISIBLE
            tv_my_btn.text = "立即开通"
        }
    }

    private fun initListener() {
        ll_my_login.setOnClickListener(this)
        tv_my_btn.setOnClickListener(this)
        tv_my_account.setOnClickListener(this)
        ll_my_record.setOnClickListener(this)
        ll_my_feed.setOnClickListener(this)
        ll_my_payrecord.setOnClickListener(this)
        ll_my_setting.setOnClickListener(this)
        ll_contactus.setOnClickListener(this)
        btn_action.setOnClickListener(this)
        rl_lucky.setOnClickListener(this)
    }


    //----9宫格逻辑--开始--//
    override fun unlockSuc() {
//        myPresenter.showTurn()

        if (nineShowBean != null) {
            if (nineShowBean!!.need - nineShowBean!!.complete-1>0) {
                showContinueDialog()
            }
        }
    }

    override fun getTurnIphoneMsgSuc(data: NineListBean) {
        lucky_panel.setImgArray(data.list)
        initLuckyIndexForPid(data.list)
    }

    private fun initLuckyIndexForPid(list: List<NineListBean.NineBean>) {
        if (list != null && list.size > 0) {
            for (i in 0 until list.size) {
                luckyIndexMap.put(i, list.get(i).pid ?: i.toString())
            }
        }
    }

    override fun toTurnSuc(data: NineListBean.NineBean) {
        Handler(Looper.getMainLooper()).postDelayed({
            startNine(data)
        }, 500)
    }

    override fun showTurnSuc(data: NineShowBean) {
        AppPreferencesManager.get()
            .put(Constant.LUCKY_FLAG, data.isShow)
        nineShowBean = data
        if (data.isShow) {
            // 加载一次转盘数据
            if (!isInitLuckyData) {
                myPresenter.getTurnIphoneMsg()

                btn_action?.postDelayed({
                    yoyo = YoYo.with(Techniques.Pulse).duration(1000).repeat(-1).playOn(btn_action)
                }, 200)
                isInitLuckyData = true
            }

            rl_lucky.visibility = View.VISIBLE
            if (TextUtils.equals(
                    carrierType,
                    Constant.CARRIERTYPE_NINE3
                ) && data.complete >= data.need
            ) {
                carrierType = Constant.CARRIERTYPE_NINE
                myPresenter.toTurn()
            }
            tv_nine_count.text = "${data.complete}/${data.need}次"
        } else {
            rl_lucky.visibility = View.GONE
        }
    }

    private fun luckyAward() {
        if (nineShowBean != null) {
            if (nineShowBean!!.complete >= nineShowBean!!.need) {
                carrierType = Constant.CARRIERTYPE_NINE3
            }
        }
        AdManager.instance.showAd(requireActivity(), carrierType,
            object : AdStatusListener {
                var canFail = false
                override fun adSuccess() {
                    canFail = true
                }

                override fun adFail() {
                    if (canFail) return

                    NoPreAdManager.loadVideoAd(
                        requireActivity(),
                        carrierType, object : AdStatusListener {
                            override fun adFail() {
                                carrierType = Constant.CARRIERTYPE_NINE
                                showToast("广告太火爆了，请稍候再试")
                            }

                            override fun adSuccess() {
                            }

                            override fun adClose(vo: HashMap<String, Any>?) {
                                vo?.let {
                                    myPresenter.unlock(vo)
                                }
                            }
                        })
                }

                override fun adClose(vo: HashMap<String, Any>?) {
                    vo?.let {
                        myPresenter.unlock(vo)
                    }
                }

            })

    }

    private fun startNine(data: NineListBean.NineBean) {
        if (data.pid == null) {
            showToast("抽奖产品未配置")
            return
        }

        if (!lucky_panel.isGameRunning) {
            lucky_panel.startGame()

            RxjavaUtil.executeRxTask(object : CommonRxTask<String>("") {
                override fun doInIOThread() {
                    Thread.sleep(3000)
                }

                override fun doInUIThread() {
                    val index = getLuckyIndex(data.pid)
                    lucky_panel.tryToStop(index)

                    Handler(Looper.getMainLooper()).postDelayed({
                        val bundle = Bundle()
                        bundle.putString(NinePayActivity.PID, data.pid)
                        bundle.putString(NinePayActivity.TITLE, data.title)
                        bundle.putString(NinePayActivity.TYPE, data.type)
                        readyGo(NinePayActivity::class.java, bundle)
                    }, 1500)
                }
            })
        }
    }

    private fun getLuckyIndex(pid: String): Int {
        if (luckyIndexMap.size > 0) {
            for ((key, value) in luckyIndexMap) {
                if (TextUtils.equals(pid, value)) {
                    return key
                }
            }
        }

        return 1
    }

    // 点击九宫格按钮
    private fun clickTurn() {
        if (luckyIndexMap.size == 0) {
            showToast("界面初始异常，请重新进入")
            return
        }

        if (nineShowBean != null) {
            if (nineShowBean!!.complete != nineShowBean!!.need) {
                val luckyFirst =
                    AppPreferencesManager.get().getBoolean(Constant.LUCKY_MY_FIRST, false)
                if (!luckyFirst) {
                    isTurnLuckyPage=true
                    AppPreferencesManager.get().put(Constant.LUCKY_MY_FIRST, true)
                    val bundle = Bundle()
                    bundle.putInt(NineKnowActivity.COMPLETE, nineShowBean!!.complete)
                    bundle.putInt(NineKnowActivity.NEED, nineShowBean!!.need)
                    readyGo(NineKnowActivity::class.java, bundle)
                    return
                }
            }
        }

        luckyAward()
    }

    // 继续观看逻辑
    private fun showContinueDialog() {
        nineShowBean?.let {
            NineContinueDialog(
                requireActivity(),
                it.need - it.complete - 1,
                object : DialogListener() {
                    override fun onClick(dialog: Dialog?, v: View?) {
                        super.onClick(dialog, v)
                        dialog?.dismiss()
                        clickTurn()
                    }
                }).show()
        }
    }
    //----9宫格逻辑--结束--//

    private fun showAd() {
        MyExpressManager.instance.getAdView(object : ExpressAdCallback {
            override fun loadSuccess(adView: FrameLayout?) {
                adView?.let {
                    UIUtils.removeFromParent(it)
                    fl_ad.removeAllViews()
                    fl_ad.addView(it)
                }

                MyExpressManager.instance.preLoadAd()
            }

            override fun renderSuccess(adView: FrameLayout?): Boolean {
                adView?.let {
                    UIUtils.removeFromParent(it)
                    fl_ad.removeAllViews()
                    fl_ad.addView(it)
                }

                MyExpressManager.instance.preLoadAd()
                return false
            }

            override fun loadFail() {
            }
        })
    }
}