package com.mints.goodmoney.ui.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.Platform.ShareParams
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.component.dly.xzzq_ywsdk.YwSDK_WebActivity.Companion.open
import com.mints.goodmoney.BuildConfig
import com.mints.goodmoney.R
import com.mints.goodmoney.ad.video.VedioAdingManager
import com.mints.goodmoney.common.AppConfig
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.manager.BxmManager
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.mvp.model.*
import com.mints.goodmoney.mvp.presenters.MyPresenter
import com.mints.goodmoney.mvp.views.MyView
import com.mints.goodmoney.ui.activitys.*
import com.mints.goodmoney.ui.adapter.GvMyAdapter
import com.mints.goodmoney.ui.adapter.MainMyAdapter
import com.mints.goodmoney.ui.adapter.listener.OnItemChildClickListener
import com.mints.goodmoney.ui.fragment.base.BaseFragment
import com.mints.goodmoney.utils.ImageUtil
import com.mints.goodmoney.utils.SpanUtils
import com.mints.library.net.netstatus.NetUtils
import com.mints.library.utils.ConstantUtil
import com.mints.library.utils.GlideUtils
import com.mints.library.utils.nodoubleclick.AntiShake
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.fragment_main_my.*
import kotlinx.android.synthetic.main.header_layout.*
import kotlinx.android.synthetic.main.item_fragment_main_my_bottom.*
import kotlinx.android.synthetic.main.item_fragment_main_my_clock.*
import kotlinx.android.synthetic.main.item_fragment_main_my_promotions.*
import kotlinx.android.synthetic.main.item_fragment_main_my_title.*
import kotlinx.android.synthetic.main.view_title.*
import java.util.*

/**
 * 描述：我
 * 作者：孟崔广
 * 时间：2020/6/4 17:30
 */
@SuppressLint("SetTextI18n")
class MyFragment : BaseFragment(), MyView, OnItemChildClickListener, OnRefreshListener, View.OnClickListener, AdapterView.OnItemClickListener {

    private val myPresenter by lazy { MyPresenter() }
    private val userManager by lazy { UserManager.getInstance() }
    private lateinit var vedioAdingManager: VedioAdingManager
    private var loadVedioFailCount = 0

    private var userConfig: MyInfo? = null
    private var hotList: List<BannerBean.ListBean>? = arrayListOf()

    // 当天签到金币
    private var curSignCoin = 50

    // 签到信息
    private var signCardBean: SignCardBean? = null

    // 任务数据
    private val dataList: MutableList<MyInfo.AutoListBean> = mutableListOf()
    private var mainMyAdapter: MainMyAdapter? = null

    // 轮播图只展示一次
    private var bannerFlag = false

    override fun getContentViewLayoutID() = R.layout.fragment_main_my

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

        vedioAdingManager = VedioAdingManager.getInstance(activity)

        initView()
        initRecy()

        if (!TextUtils.isEmpty(userManager.userID)) {
            myPresenter.getAutoUserHallBaseMsg()

            // 登录成功的用户初始化鱼丸盒子
            if (userManager.userIsLogin()) {
                baseApplication.initYwSdk()
            }
        } else {
            // 游客登录
            myPresenter.userLogin()
        }
    }

    private fun initView() {
        tv_title.text = "个人中心"
        view_title.text = "每日任务"

        item_iv_settings.setOnClickListener(this)
        item_title_id.setOnClickListener(this)
        iv_right_icon.setOnClickListener(this)
        btn_withdraw.setOnClickListener(this)
        btn_coinRecord.setOnClickListener(this)
        item_title_invitecode.setOnClickListener(this)
        item_title_invitecode_copy.setOnClickListener(this)
        ll_my_login.setOnClickListener(this)

        item_promotions_egv.onItemClickListener = this
        item_bottom_version.text = "v" + ConstantUtil.getVersionName(mContext)
    }

    /**
     * 初始化Recyclerview
     */
    private fun initRecy() {
        recy_my.addItemDecoration(DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL))
        recy_my.setItemViewCacheSize(10)
        mainMyAdapter = MainMyAdapter(mContext, dataList)
        recy_my.adapter = mainMyAdapter
        mainMyAdapter?.setOnItemChildClickListener(this)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (hidden) { // 不在最前端界面显示
            onPause()
        } else { // 重新显示到最前端中
            onResume()
        }
        super.onHiddenChanged(hidden)
    }

    override fun onResume() {
        super.onResume()
        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_MY) {
            if (!TextUtils.isEmpty(userManager.userID)) {
                myPresenter.getAutoUserHallBaseMsg()
            } else {
                // 游客登录
                myPresenter.userLogin()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        BxmManager.onDestory()
        myPresenter.detachView()
    }

    override fun getUserTaskMsgSuc(data: MyInfo?) {
        srl_my.finishRefresh(true)

        if (data == null) {
            userConfig = null
            return
        }

        myPresenter.getSignInHomePageMsg()
        if (!bannerFlag) {
            myPresenter.myHotActivity()
        }
        myPresenter.getHallBaseMsg()

        userConfig = data
        handleRecyData()
        setUserLoginStatus()
    }

    override fun getUserTaskMsgFail() {
        srl_my.finishRefresh(false)

        userConfig = null
        item_promotions_egv.visibility = View.GONE
        setUserLoginStatus()
    }

    override fun getMyHotActivitySuc(data: BannerBean?) {
        if (activity != null && !requireActivity().isFinishing) {
//        item_promotions_egv.visibility = View.GONE
            if (!bannerFlag) {
                bannerFlag = true
                data?.let {
                    item_promotions_egv.visibility = View.VISIBLE
                    hotList = it.list
                    item_promotions_egv.adapter = GvMyAdapter(mContext, requireActivity(), hotList)
                }
            }
        }
    }

    override fun getSignInHomePageMsgSuc(signBean: SignCardBean?) {
        if (signBean == null) {
            signCardBean = null
            return
        }

        signCardBean = signBean
        // 初始化签到
        setSignDayLayout(signCardBean!!)
    }

    override fun signInHomePageSuc() {
        if (signCardBean == null) {
            showToast("网络异常,请检测网络！")
            myPresenter.getSignInHomePageMsg()
            return
        }

        myPresenter.getSignInHomePageMsg()

        val bundle = Bundle()
        bundle.putInt(Constant.MAIN_CUR_COIN, curSignCoin)
        bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_SIGNIN_HOMEPAGE_AWARD)
        readyGo(AwardActivity::class.java, bundle)
    }

    override fun userLoginSuc() {
        myPresenter.getAutoUserHallBaseMsg()
        myPresenter.getHallBaseMsg()
    }

    override fun getHallBaseMsgSuc(data: UserTaskMsgBean) {
        if (activity == null || activity!!.isFinishing) {
            return
        }

        // 新人福利
        if (data.userMsg.firstGiveCoin > 0) {
            val bundle = Bundle()
            bundle.putInt(Constant.MAIN_CUR_COIN, data.userMsg.firstGiveCoin)
            bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_NEW_USER)
            readyGo(AwardActivity::class.java, bundle)
        } else {
            // 离线收益
            if (data.offlineBean.offlineIncome > 0) {
                val bundle = Bundle()
                bundle.putInt(Constant.MAIN_CUR_COIN, data.offlineBean.offlineIncome)
                bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_OFFLINE_DOUBLE)
                readyGo(AwardActivity::class.java, bundle)
            }
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        if (userManager.userID.isNotEmpty()) {
            myPresenter.getAutoUserHallBaseMsg()
        } else {
            myPresenter.userLogin()
        }
    }

    /**
     * 设置签到样式
     *
     * @param signCardBean
     */
    private fun setSignDayLayout(signCardBean: SignCardBean) {
        ll_my_sign.visibility = View.VISIBLE
        val nowDate = signCardBean.nowDate
        var signStatus = 0 //0-未签到 1-已签到 2-已签到且看了视频
        val signList = signCardBean.list
        if (signList != null && signList.size > 0) {
            val signGoldList = ArrayList<Int>()
            val signViewBean = SignViewBean()
            for (i in signList.indices) {
                val signBean = signList[i]
                val signDays = signBean.d
                // 初始化每天的金币
                when (signDays) {
                    1 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.firstStatus = signBean.status
                    }
                    2 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.twoStatus = signBean.status
                    }
                    3 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.threeStatus = signBean.status
                    }
                    4 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.fourStatus = signBean.status
                    }
                    5 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.fiveStatus = signBean.status
                    }
                    6 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.sixStatus = signBean.status
                    }
                    7 -> {
                        signGoldList.add(signBean.coin)
                        signViewBean.sevenStatus = signBean.status
                    }
                }

                // 获取当天状态
                if (nowDate == signDays) {
                    signStatus = signBean.status
                    curSignCoin = signBean.coin
                }
            }

            // 初始化金币数据
            item_clock_signview.initSignViewGoldLayout(signGoldList)
            // 设置签到样式
            item_clock_signview.setSignViewLayout(signViewBean)
            // 重新设置当天签到样式
            item_clock_signview.setCurDaysSignViewLayout(nowDate, signStatus)
            if (signStatus == 0) {
                myPresenter.signInHomePage()
            }
        }

        // 根据当天状态 计算连续签到天数
        val alwaysSignDay = if (signStatus == 0) {
            nowDate - 1
        } else {
            nowDate
        }
        item_clock_signday.text = SpanUtils()
                .append("  已连续签到").setForegroundColor(mContext.resources.getColor(R.color.product_text))
                .append(" $alwaysSignDay ").setForegroundColor(mContext.resources.getColor(R.color.versus_sign_day))
                .append("天").setForegroundColor(mContext.resources.getColor(R.color.product_text))
                .create()
        val finalSignStatus = signStatus
        item_clock_signview.setSignViewListener { day ->
            if (nowDate == day) {
                RxPermissions(requireActivity())
                        .request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe { granted: Boolean ->
                            if (granted) {
//                                if (userManager.adShowFlag) {
                                if (finalSignStatus == 0) {
                                    myPresenter.signInHomePage()
                                } else if (finalSignStatus == 1) {
                                    val bundle = Bundle()
                                    bundle.putInt(Constant.MAIN_CUR_COIN, curSignCoin * 2)
                                    bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_SIGNIN_HOMEPAGE_CARD)
                                    readyGo(AwardActivity::class.java, bundle)
                                }
//                                }
                            } else {
                                showMissingPermissionDialog("设备、储存")
                            }
                        }
            }
        }
    }

    private fun setUserLoginStatus() {
        if (userConfig != null) {
            item_title_invitecode.text = "邀请码：" + userConfig!!.userMsg.idcode
        }

        if (userManager.userIsLogin()) {
            // 已登录
            if (userManager.wxOpenid.isNotEmpty()) {
                GlideUtils.loadImageViewLoding(context, userManager.wxHeader, item_title_avatar, R.mipmap.ic_my, R.mipmap.ic_my)
                item_title_id.text = userManager.wxName
            } else {
                var mobile = userManager.mobile
                if (mobile.isNotEmpty()) {
                    mobile = mobile.substring(0, 3) + "****" + mobile.substring(mobile.length - 4, mobile.length)
                }
                item_title_id.text = "手机:$mobile"
                item_title_avatar.setImageResource(R.mipmap.ic_my)
            }
        } else {
            // 未登录
            var userId = userManager.userID
            if (userId.isNotEmpty() && userId.length > 11) {
                userId = userId.substring(userId.length - 10)
                item_title_id.text = "游客$userId 去登录"
            } else {
                item_title_id.text = "游客 去登录"
            }
            item_title_avatar.setImageResource(R.mipmap.ic_my)
        }
        if (BuildConfig.DEBUG) {
            item_title_invitecode.text = "-" + item_title_invitecode.text
        }

        val userGold = if (userConfig == null) {
            "0.00"
        } else {
            "" + userConfig!!.userMsg.coin
        }

        // 金币
        item_title_gold_count.text = userGold
    }

    /**
     * 处理列表数据
     */
    private fun handleRecyData() {
        dataList.clear()

        dataList.addAll(userConfig!!.autoList)

//        // 跳转首页视频
//        val task1 = TaskBean(R.mipmap.icon_my_coin, "分分钟赚金币，翻倍还能赚更多", "", "去赚钱", 1)
//        // 邀好友赚金币
//        var progressStrInvited = ""
//        var btnStr = ""
//        if (userConfig != null) {
//            progressStrInvited = "(" + userConfig!!.taskShareFriend.complete + "/" + userConfig!!.taskShareFriend.max + ")"
//            if (userConfig!!.taskShareFriend.complete == userConfig!!.taskShareFriend.max) {
//                btnStr = "已完成"
//            } else {
//                btnStr = if (userConfig!!.taskShareFriend.status == 0) "去邀请" else "立即领取"
//            }
//        }
//        val task2 = TaskBean(R.mipmap.icon_my_invite, "邀好友,赚金币", progressStrInvited, btnStr, 2)
//        // 看福利视频赚金币
//        var progressStrVideo = ""
//        var task3Str = ""
//        if (userConfig != null) {
//            progressStrVideo = "(" + userConfig!!.taskVeido.complete + "/" + userConfig!!.taskVeido.max + ")"
//            if (userConfig!!.taskVeido.complete == userConfig!!.taskVeido.max) {
//                task3Str = "已完成"
//            } else {
//                task3Str = "赚金币"
//            }
//        }
//        val task3 = TaskBean(R.mipmap.icon_my_video, "看福利视频赚金币", progressStrVideo, task3Str, 3)
//        // 玩游戏，赚金币
//        var task4Str = ""
//        if (userConfig != null) {
//            task4Str = if (userConfig!!.taskGame.status == 0) "赚金币" else (if (userConfig!!.taskGame.status == 1) "立即领取" else "已完成")
//        }
//        val task4 = TaskBean(R.mipmap.icon_my_game, "玩游戏，赚金币", "", task4Str, 4)
//        // 小说免费看，金币大家赚
////        val task5 = TaskBean(R.mipmap.icon_my_fiction, "小说免费看，金币大家赚", "", "去阅读", 5)
//        // 试玩平台
//        val task6 = TaskBean(R.mipmap.icon_my_demo, "试玩平台", "", "赚金币", 5)
//        dataList.add(task1)
//        dataList.add(task2)
//        dataList.add(task3)
//        dataList.add(task4)
////        dataList.add(task5)
//        dataList.add(task6)

        mainMyAdapter?.notifyDataSetChanged()
    }

    override fun onItemChildClick(view: View?, position: Int) {
        if (AntiShake.check(view?.id)) return

        if (!NetUtils.isNetworkConnected(context)) {
            showToast("网络异常,请检测网络")
            return
        }

        when (view?.id) {
            R.id.item_task_click -> {
                val taskBean = dataList[position]
                when (taskBean.baseConfig.taskId) {
                    // 跳转首页视频
                    MainMyAdapter.TO_HOME -> {
                        val activity: MainActivity? = activity as MainActivity?
                        activity?.clickTab1Layout()
                        activity?.selectVedio()
                    }
                    // 邀好友赚金币
                    MainMyAdapter.APP_SHAREFRIEND -> {
                        if (taskBean.otherConfig != null) {
//                            if (taskBean.otherConfig.complete >= taskBean.otherConfig.max) {
//                                showToast("邀好友赚金币任务已完成，请明日再来")
//                                return
//                            }

                            when (taskBean.otherConfig.status) {
                                0 -> {
                                    val wechatSp = ShareParams()
                                    wechatSp.shareType = Platform.SHARE_WEBPAGE
                                    wechatSp.title = Constant.SHARE_TITLE
                                    wechatSp.text = Constant.SHARE_CONTENT
                                    wechatSp.imageData = ImageUtil.drawableToBitmap(ContextCompat.getDrawable(requireContext(), R.mipmap.ic_launcher))
                                    wechatSp.url = Constant.SHARE_URL
                                    val wechat = ShareSDK.getPlatform(Wechat.NAME)
                                    if (wechat.isClientValid) {
                                        myPresenter.cmtShareStatus()
                                        // 执行图文分享
                                        wechat.share(wechatSp)
                                    } else {
                                        showToast("请先安装微信")
                                    }
                                }
                                1 -> {
//                                    if (taskBean.otherConfig.complete < taskBean.otherConfig.max) {
                                    val bundle = Bundle()
                                    bundle.putInt(Constant.MAIN_CUR_COIN, taskBean.otherConfig.coin)
                                    bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CHALLENGE_SHAREFRIEND)
                                    readyGo(AwardActivity::class.java, bundle)
//                                    }
                                }
                                2 -> {
                                    val wechatSp = ShareParams()
                                    wechatSp.shareType = Platform.SHARE_WEBPAGE
                                    wechatSp.title = Constant.SHARE_TITLE
                                    wechatSp.text = Constant.SHARE_CONTENT
                                    wechatSp.imageData = ImageUtil.drawableToBitmap(ContextCompat.getDrawable(requireContext(), R.mipmap.ic_launcher))
                                    wechatSp.url = Constant.SHARE_URL
                                    val wechat = ShareSDK.getPlatform(Wechat.NAME)
                                    if (wechat.isClientValid) {
                                        myPresenter.cmtShareStatus()
                                        // 执行图文分享
                                        wechat.share(wechatSp)
                                    } else {
                                        showToast("请先安装微信")
                                    }
                                }
                            }
                        }
                    }
                    // 看福利视频赚金币
                    MainMyAdapter.APP_VEDIO -> {
                        if (taskBean.otherConfig != null) {
                            if (taskBean.otherConfig.complete >= taskBean.otherConfig.max) {
                                showToast("看福利视频赚金币任务已完成，请明日再来")
                                return
                            }

                            awardVedio(taskBean.otherConfig.coin)
                        }
//                        if (userConfig!!.taskVeido!!.complete >= userConfig!!.taskVeido!!.max) {
//                            showToast("看福利视频赚金币任务已完成，请明日再来")
//                            return
//                        }

                    }
                    // 玩游戏，赚金币
                    MainMyAdapter.TO_LIEBAO -> {
                        if (taskBean.otherConfig != null) {
                            when (taskBean.otherConfig.status) {
                                0 -> {
                                    readyGo(LiebaoGameActivity::class.java)
                                }
                                1 -> {
                                    val bundle = Bundle()
                                    bundle.putInt(Constant.MAIN_CUR_COIN, taskBean.otherConfig.coin)
                                    bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_GAME_ONLINE)
                                    readyGo(AwardActivity::class.java, bundle)
                                }
                                2 -> {
                                    readyGo(LiebaoGameActivity::class.java)
                                }
                            }
                        }
//                        if (taskBean.btnStr == "立即领取") {
//                            val bundle = Bundle()
//                            bundle.putInt(Constant.MAIN_CUR_COIN, userConfig?.taskGame?.coin!!)
//                            bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_GAME_ONLINE)
//                            readyGo(AwardActivity::class.java, bundle)
//                        } else {
//                            readyGo(LiebaoGameActivity::class.java)
//                        }
                    }
                    // 小说免费看，金币大家赚
//                    MainMyAdapter.TASK_TYPE_FICTION -> {
//                    }
                    // 试玩平台
                    MainMyAdapter.TO_YWHZ -> {
                        if (!userManager.userIsLogin()) {
                            readyGo(LoginActivity::class.java)
                            return
                        }

                        try {
                            activity?.let { open(it) }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            showToast("请重新退出账号登录")
                        }
                    }
                }
            }
        }
    }

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

        if (!NetUtils.isNetworkConnected(context)) {
            showToast("网络异常,请检测网络")
            return
        }

        when (v?.id) {
            R.id.ll_my_login -> {
                if (!userManager.userIsLogin()) {
                    readyGo(LoginActivity::class.java)
                }
            }
            R.id.item_title_id -> {
                if (!userManager.userIsLogin()) {
                    readyGo(LoginActivity::class.java)
                }
            }
            R.id.item_iv_settings -> {
                readyGo(SettingsActivity::class.java)
            }
            R.id.btn_withdraw -> {
                if (userConfig == null) {
                    showToast("网络异常,请检测网络！")
                    myPresenter.getAutoUserHallBaseMsg()
                    return
                }

                readyGo(DrawcashActivity::class.java)
            }
            R.id.btn_coinRecord -> {
                if (userConfig == null) {
                    showToast("网络异常,请检测网络！")
                    myPresenter.getAutoUserHallBaseMsg()
                    return
                }

                readyGo(CoinRecordActivity::class.java)
            }
            R.id.item_title_invitecode -> {
                if (userConfig != null) {
                    val invitedCode = userConfig!!.userMsg.idcode
                    if (!TextUtils.isEmpty(invitedCode)) {
                        showToast("复制成功")
                        val clipboardManager = mContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        clipboardManager.setPrimaryClip(ClipData.newPlainText("invitecode_copy", invitedCode))
                    }
                }
            }
            R.id.item_title_invitecode_copy -> {
                if (userConfig != null) {
                    val invitedCode = userConfig!!.userMsg.idcode
                    if (!TextUtils.isEmpty(invitedCode)) {
                        showToast("复制成功")
                        val clipboardManager = mContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        clipboardManager.setPrimaryClip(ClipData.newPlainText("invitecode_copy", invitedCode))
                    }
                }
            }
        }
    }

    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        if (hotList!!.isNotEmpty()) {
            val hotBean: BannerBean.ListBean = hotList!![position]

            // 自有界面
            when (hotBean.toUrl) {
                Constant.HOT_ACTIVITY_WATER -> {
                    readyGo(WaterActivity::class.java)
                }
                Constant.HOT_ACTIVITY_WALK -> {
                    readyGo(WalkActivity::class.java)
                }
                Constant.HOT_ACTIVITY_CARD -> {
                    readyGo(EraseActivity::class.java)
                }
                Constant.HOT_ACTIVITY_BXM -> {
                    // 消费变现猫事件
                }
                else -> {
                    val bundle = Bundle()
                    bundle.putString(WebActivity.WEB_TITLE, hotBean.title)
                    bundle.putString(WebActivity.WEB_URL, hotBean.url)
                    readyGo(WebActivity::class.java, bundle)
                }
            }
        }
    }

    /**
     * 获取激励视频
     */
    private fun awardVedio(coin: Int) {
        if (vedioAdingManager.vedioFinishFlag) {
            showToast("今日视频已看完，请明天再来吧")
            return
        }

        showLoading("加载中...")

        val bean = VedioAdingBean()
        bean.carrierType = Constant.CARRIER_VERSUS_VIDEO
        bean.curCoin = coin

        loadVedio(vedioAdingManager, bean, true)
    }

    /**
     * 加载激励视频
     */
    private fun loadVedio(vedioAdingManager: VedioAdingManager, bean: VedioAdingBean, isFirstLoad: Boolean) {
        vedioAdingManager.setVedioAdingListener(object : VedioAdingManager.VedioAdingListener {
            override fun vedioAdingListenerError(adType: String) {
                showToast("加载超时，请休息一下")
                hideLoading()
            }

            override fun vedioAdingListenerFail(adType: String) {
                loadVedioFailCount++
                if (loadVedioFailCount >= 2) {
                    hideLoading()
                    showToast("加载失败，请稍后重试!")
                } else {
                    loadVedio(vedioAdingManager, bean, false)
                }
            }

            override fun vedioAdingListenerSuccess(adType: String) {
                hideLoading()
                vedioAdingSuccess(adType)
            }
        })
        if (isFirstLoad) {
            // 首页按权重加载
            vedioAdingManager.loadAding(activity, bean)
        } else {
            // 失败按优先级加载
            vedioAdingManager.loadFailAding(activity, bean)
        }
    }

    private fun vedioAdingSuccess(adType: String) {
        val bundle = Bundle()
        for (autoListBean in userConfig!!.autoList) {
            if (autoListBean.baseConfig.taskId == MainMyAdapter.APP_VEDIO) {
                if (autoListBean.otherConfig != null) {
                    bundle.putInt(Constant.MAIN_CUR_COIN, autoListBean.otherConfig.coin)
                    bundle.putString(Constant.MAIN_CARRIER_TYPE, Constant.CARRIER_VERSUS_VIDEO)
                    readyGo(AwardActivity::class.java, bundle)

                    return
                }
            }
        }
    }
}