package com.ytpm.hydtw.fragment

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import com.anythink.banner.api.ATBannerListener
import com.anythink.banner.api.ATBannerView
import com.anythink.core.api.ATAdConst
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.ATShowConfig
import com.anythink.core.api.AdError
import com.anythink.interstitial.api.ATInterstitial
import com.anythink.interstitial.api.ATInterstitialListener
import com.anythink.nativead.api.ATNative
import com.anythink.nativead.api.ATNativeNetworkListener
import com.anythink.nativead.api.NativeAd
import com.anythink.rewardvideo.api.ATRewardVideoAd
import com.anythink.rewardvideo.api.ATRewardVideoListener
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.ToastUtils.MODE
import com.gyf.immersionbar.ImmersionBar
import com.ytpm.hydtw.R
import com.ytpm.hydtw.adapter.MineAdapter
import com.ytpm.hydtw.dao.Question
import com.ytpm.hydtw.dao.Record
import com.ytpm.hydtw.databinding.FragmentDatiBinding
import com.ytpm.hydtw.loading.GlobalLoading
import com.ytpm.hydtw.loading.LoadingDialog
import com.ytpm.hydtw.network.BaseRetrofit
import com.ytpm.hydtw.network.Callback2
import com.ytpm.hydtw.utils.DateTimeConverter
import com.ytpm.hydtw.utils.DateTimeUtils
import com.ytpm.hydtw.utils.GlideUtils
import com.ytpm.hydtw.utils.MediationNativeAdUtil
import com.ytpm.hydtw.utils.UserInfoSpUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter


class DatiFragment() : Fragment(), ATRewardVideoListener,
    ATBannerListener {

    private var atNative: ATNative? = null
    private var interstitialAd: ATInterstitial? = null
    private var startAdTime: String? = null
    private var endAdTime: String? = null
    private var mRewardVideoAd: ATRewardVideoAd? = null
    private var job: Job? = null
    private var scope: CoroutineScope? = null
    private var job1: Job? = null
    private var scope1: CoroutineScope? = null
    private var inAdTime: Int = 0
    private var getTlCountDownTimer: CountDownTimer? = null
    private var getTlShowBtnCountDownTimer: CountDownTimer? = null
    private var startReloadRewardVideoAd: CountDownTimer? = null
    private var useTimer: Int = 0
    private var questions: ArrayList<Question>? = arrayListOf()
    private lateinit var binding: FragmentDatiBinding
    private var nowIndex = 0
    private var tl = 0

    private var jrdd = 0
    private var lsdd = 0

    private var getTlTime = 20
    private var getTlShowBtnTime = 8

    private var isGrDialogShow = false
    private var isGetTlDialogShow = false

    private var isGetResult = false
    private var isInAdPaunse = false

    private var loadDialog: LoadingDialog? = null
    private var loadingTime = 10

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentDatiBinding.inflate(inflater)
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .titleBar(null)
            .init()
        loadAd()
        initData()
        initUserTime()
        initInAdTime()
        loadBannerAd()
        loadNativeAd()
        loadInterstitial()
        initView()
        useTimer = 0
        return binding.root
    }

    private fun initView() {

        val headImg = UserInfoSpUtils().getHeadImg()

        if (headImg.isNotEmpty()) {
            context?.let {
                GlideUtils().circelImages(it, headImg, binding.dialogGettlHead)
                GlideUtils().circelImages(it, headImg, binding.fragmentDatiHead)
                GlideUtils().circelImages(it, headImg, binding.dialogSetHead)
            }
        }

        val registerTime = UserInfoSpUtils().getRegistryTime()
        val ddd = DateTimeConverter.convertToBeijingTime(registerTime, "yyyy/MM/dd HH:mm:ss")
        binding.dialogGettlRegisterTime.text = "注册时间:${ddd}"
        binding.dialogSetRegisterTime.text = "注册时间:${ddd}"

        val loginTime = UserInfoSpUtils().getLoginTime()
        val ccc = DateTimeConverter.convertToBeijingTime(loginTime, "yyyy/MM/dd HH:mm:ss")
        binding.dialogGettlLoginTime.text = "登录时间:${ccc}"

        val uid = UserInfoSpUtils().getUserId()
        binding.fragmentDatiUid.text = uid
        binding.dialogGettlUserid.text = uid
        binding.dialogSetUserid.text = uid

        val nickname = UserInfoSpUtils().getNickName()
        binding.dialogSetNickname.text = nickname
        binding.dialogGettlNickname.text = nickname

        jrdd = UserInfoSpUtils().getTodayAnswerCount()
        lsdd = UserInfoSpUtils().getHistoryAnswerCount()

        binding.jrddTv.text = "今日答题: ${jrdd}题"
        binding.lsddTv.text = "历史答题: ${lsdd}题"

        tl = UserInfoSpUtils().getPower()
        binding.tlValue.text = "体力:${tl}"

        binding.switch1.isChecked = true
        binding.switch2.isChecked = true

        startGetTlTime()

        startGetTlShowBtnTime()

        initGetTlTime()

        binding.dialogGr.setOnClickListener {

        }

        binding.fragmentDatiGr.setOnClickListener {
            this.isGrDialogShow = !isGrDialogShow
            if (isGrDialogShow) {
                binding.dialogGr.visibility = View.VISIBLE
            } else {
                binding.dialogGr.visibility = View.GONE
            }
        }

        binding.dialogGrClose.setOnClickListener {
            this.isGrDialogShow = false
            binding.dialogGr.visibility = View.GONE
        }

        binding.getTlCl.setOnClickListener {

            if (getTlTime > 0) {
                ToastUtils.showShort("等待倒计时结束！")
                return@setOnClickListener
            }

            if (isGetTlDialogShow) {
                this.isGetTlDialogShow = false
                binding.dialgoGettlLl.visibility = View.GONE
            } else {
                this.isGetTlDialogShow = true
                binding.dialgoGettlLl.visibility = View.VISIBLE
            }

            getTlShowBtnCountDownTimer?.start()
        }

        binding.dialgoGettlLl.setOnClickListener { }

        binding.dialotGettlBtnTx.setOnClickListener {
            showAd()
        }
        binding.getTlDialogClose.setOnClickListener {
            this.isGetTlDialogShow = false
            binding.dialgoGettlLl.visibility = View.GONE
            initGetTlBtnTime()
        }

        binding.a1.setOnClickListener {
            if (isGetResult) {
                return@setOnClickListener
            }
            gameResult(0)
        }

        binding.a2.setOnClickListener {
            if (isGetResult) {
                return@setOnClickListener
            }
            gameResult(1)
        }

        initDialogGetTl()
    }

    private fun initUserTime() {
        if (job == null) {
            job = Job()
        }

        if (scope == null) {
            scope = CoroutineScope(Dispatchers.Main + job!!)
        }

        scope!!.launch {
            while (isActive) {
                useTimer++
                delay(1000)
            }
        }
    }

    private fun initInAdTime() {
        if (job1 == null) {
            job1 = Job()
        }

        if (scope1 == null) {
            scope1 = CoroutineScope(Dispatchers.Main + job1!!)
        }

        scope1!!.launch {
            while (isActive) {
                if (!isInAdPaunse) {
                    inAdTime++
                    if (inAdTime == 60) {

                        interstitialAd?.show(activity, getATShowConfig1())
                        job1?.cancel()
                        scope1?.cancel()
                        job1 = null
                        scope1 = null
                        inAdTime = 0
                    }
                }
                delay(1000)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        this.isInAdPaunse = true
    }

    override fun onResume() {
        super.onResume()
        this.isInAdPaunse = false
    }

    private fun initDialogGetTl() {

        val adapter = MineAdapter(initDataAdapter())
        binding.dialgoGettlRl.adapter = adapter

        binding.dialogGettlJrdd.text = "今日答题: ${jrdd}题"
        binding.dialogGettlLsdd.text = "历史答题: ${lsdd}题"

    }

    private fun initDataAdapter(): MutableList<Record> {
        val dfdfd = UserInfoSpUtils().getAnswerRecordList()
        return dfdfd.toMutableList()
    }

    private fun answer(questionId: String, itemId: String) {

        val map = HashMap<String, Any>()
        map["duration"] = useTimer
        map["itemId"] = itemId
        map["questionId"] = questionId
        map["userId"] = UserInfoSpUtils().getUserId()

        val requestBody = BaseRetrofit.getRequestBodyByMapToJson(map)
        BaseRetrofit.getInstance().apiService.answerQuestion(requestBody)
            .enqueue(object : Callback2<Any>() {
                override fun success(body: Any?) {
                    val userinfo = UserInfoSpUtils().getUserInfo()

                    var answerTime = ""

                    // 格式化为ISO字符串
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        val instant = Instant.now()
                        val formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
                        answerTime = instant.atZone(ZoneId.of("UTC")).format(formatter)
                    } else {
                        answerTime = DateTimeUtils.getCurrentDateTimeIso().toString()
                    }

                    val record = Record(answerTime)
                    val ddd = UserInfoSpUtils().getUserInfo().answerRecordList as MutableList
                    ddd.add(0, record)

                    userinfo.answerRecordList = ddd
                    userinfo.lastQuestionId = questionId
                    UserInfoSpUtils().changeValue(userinfo)
                    initDialogGetTl()

                    useTimer = 0
                }

                override fun fail(msg: String?) {
                    ToastUtils
                        .make()
                        .setMode(MODE.DARK)
                        .setGravity(Gravity.CENTER, 0, 0)
                        .setTopIcon(R.mipmap.icon_fail)
                        .setDurationIsLong(true)
                        .show(msg)
                }
            })
    }

    private fun addPower() {

        val userId = UserInfoSpUtils().getUserId()
        BaseRetrofit.getInstance().apiService.addPower(userId).enqueue(object : Callback2<Any>() {
            override fun success(body: Any?) {
                tl++

                val user = UserInfoSpUtils().getUserInfo()
                user.power = tl
                UserInfoSpUtils().changeValue(user)

                isGetTlDialogShow = false
                binding.dialgoGettlLl.visibility = View.GONE
                changeLever()
                initGetTlBtnTime()
                initGetTlTime()
            }

            override fun fail(msg: String?) {
                ToastUtils
                    .make()
                    .setMode(MODE.DARK)
                    .setGravity(Gravity.CENTER, 0, 0)
                    .setTopIcon(R.mipmap.icon_fail)
                    .setDurationIsLong(true)
                    .show(msg)
            }
        })
    }

    @SuppressLint("SetTextI18n")
    private fun initGetTlTime() {
        binding.zz.visibility = View.VISIBLE
        getTlTime = 20
        binding.zz.text = "${getTlTime}s"
        getTlCountDownTimer?.start()
    }

    @SuppressLint("SetTextI18n")
    private fun initGetTlBtnTime() {
        binding.dialotGettlBtnTx.visibility = View.GONE
        binding.getTlDialogClose.visibility = View.GONE
        binding.dialgoGettlTime.visibility = View.VISIBLE
        getTlShowBtnTime = 8
        binding.dialgoGettlTime.text = "${getTlShowBtnTime}s"
    }

    private fun startGetTlShowBtnTime() {

        if (getTlShowBtnCountDownTimer != null) {
            return
        }
        this.getTlShowBtnTime = 8
        getTlShowBtnCountDownTimer =
            object : CountDownTimer((getTlShowBtnTime * 1000).toLong(), 1000) {
                @SuppressLint("SetTextI18n")
                override fun onTick(millisUntilFinished: Long) {
                    val secondsRemaining = millisUntilFinished / 1000
                    getTlShowBtnTime--
                    binding.dialgoGettlTime.text = "${secondsRemaining}s"
                }

                override fun onFinish() {
                    binding.dialgoGettlTime.visibility = View.GONE
                    binding.dialotGettlBtnTx.visibility = View.VISIBLE
                    binding.getTlDialogClose.visibility = View.VISIBLE
                }
            }
    }

    private fun startGetTlTime() {

        if (getTlCountDownTimer != null) {
            return
        }

        this.getTlTime = 20
        getTlCountDownTimer = object : CountDownTimer((getTlTime * 1000).toLong(), 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {
                val secondsRemaining = millisUntilFinished / 1000
                getTlTime--
                binding.zz.text = "${secondsRemaining}s"
            }

            override fun onFinish() {
                binding.zz.visibility = View.GONE
            }
        }
    }

    private fun startReloadRewardVideoAd() {

        if (startReloadRewardVideoAd != null) {
            return
        }

        startReloadRewardVideoAd = object : CountDownTimer((loadingTime * 1000).toLong(), 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {
                ToastUtils.showShort("非法操作，请30秒后重新获取！")
                if (loadDialog?.isShowing == true) loadDialog?.dismiss()
            }
        }
    }

    private fun initLever() {
        val lastQuestionId = UserInfoSpUtils().getLastQuestionId()
        questions?.forEachIndexed { index, question ->
            if (question.questionId.equals(lastQuestionId)) {
                nowIndex = index + 1
                if (nowIndex >= (questions?.size?.minus(1)!!)) {
                    nowIndex = 0
                }
            }
        }
    }

    private fun initData() {

        BaseRetrofit.getInstance().apiService.questions.enqueue(object :
            Callback2<List<Question>>() {
            override fun success(body: List<Question>?) {
                binding.answerCl.visibility = View.VISIBLE
                questions = arrayListOf()
                body?.forEach { item ->
                    if (item.itemList.size == 2) {
                        questions?.add(item)
                    }
                }
                if (questions.isNullOrEmpty()) {
                    ToastUtils
                        .make()
                        .setMode(MODE.DARK)
                        .setGravity(Gravity.CENTER, 0, 0)
                        .setTopIcon(R.mipmap.icon_fail)
                        .setDurationIsLong(true)
                        .show("题目异常，请联系程序猿！")
                    return
                }

                initLever()
                changeLever()
            }

            override fun fail(msg: String?) {
                ToastUtils
                    .make()
                    .setMode(MODE.DARK)
                    .setGravity(Gravity.CENTER, 0, 0)
                    .setTopIcon(R.mipmap.icon_fail)
                    .setDurationIsLong(true)
                    .show(msg)
            }
        })
    }

    private fun setBackGround(view: View, resId: Int) {
        view.background = ResourcesCompat.getDrawable(resources, resId, null)
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("SetTextI18n")
    private fun gameResult(btnIndex: Int) {
        val item = questions?.get(nowIndex)
        if (item?.correctItem == item?.itemList?.get(btnIndex)?.itemId) {
            when (btnIndex) {
                0 -> {
                    setBackGround(binding.a1, R.mipmap.icon_success_anseer)
                    binding.a1Result.visibility = View.VISIBLE
                    setBackGround(binding.a1Result, R.mipmap.icon_success)
                }

                1 -> {
                    setBackGround(binding.a2, R.mipmap.icon_success_anseer)
                    binding.a2Result.visibility = View.VISIBLE
                    setBackGround(binding.a2Result, R.mipmap.icon_success)
                }
            }
        } else {
            when (btnIndex) {
                0 -> {

                    setBackGround(binding.a1, R.mipmap.icon_fail_anseer)
                    binding.a1Result.visibility = View.VISIBLE
                    setBackGround(binding.a1Result, R.mipmap.icon_fail)
                }

                1 -> {
                    setBackGround(binding.a2, R.mipmap.icon_fail_anseer)
                    binding.a2Result.visibility = View.VISIBLE
                    setBackGround(binding.a2Result, R.mipmap.icon_fail)
                }
            }
        }

        if (nowIndex == (questions?.size?.minus(1))) {
            nowIndex = 0
        } else {
            nowIndex++
        }
        jrdd++
        lsdd++

        val user = UserInfoSpUtils().getUserInfo()
        user.todayAnswerCount = jrdd
        user.historyAnswerCount = lsdd
        UserInfoSpUtils().changeValue(user)

        binding.jrddTv.text = "今日答题: ${jrdd}题"
        binding.lsddTv.text = "历史答题: ${lsdd}题"

        val questionId = item?.questionId
        val itemId = item?.itemList?.get(btnIndex)?.itemId



        if (questionId != null && itemId != null) {
            answer(questionId, itemId)
        } else {
            ToastUtils.showShort("参数异常！")
        }

        GlobalScope.launch {
            isGetResult = true
            delay(3000)
            isGetResult = false
            tl--

            val user = UserInfoSpUtils().getUserInfo()
            user.power = tl
            UserInfoSpUtils().changeValue(user)

            GlobalScope.launch(Dispatchers.Main) { changeLever() }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun changeLever() {

        binding.tlValue.text = "体力:${tl}"
        binding.gkValue.text = "关卡:${nowIndex + 1}"

        setBackGround(binding.a1, R.mipmap.icon_nomal_btn)
        binding.a1Result.visibility = View.GONE
        setBackGround(binding.a2, R.mipmap.icon_nomal_btn)
        binding.a2Result.visibility = View.GONE

        val data = questions?.get(nowIndex)
        binding.content.text = data?.questionContent

        data?.itemList?.forEachIndexed { index, item ->
            when (index) {
                0 -> binding.a1.text = item.itemContent
                1 -> binding.a2.text = item.itemContent
            }
        }

        changeTran()
    }

    private fun changeTran() {

        if (tl <= 0) {
            binding.a1Tran.visibility = View.VISIBLE
            binding.a1.isClickable = false
            binding.a2Tran.visibility = View.VISIBLE
            binding.a2.isClickable = false

            ToastUtils.make().setTopIcon(R.mipmap.icon_fail)
            ToastUtils.showShort("体力不足，请先领取")
        } else {
            binding.a1Tran.visibility = View.GONE
            binding.a1.isClickable = true
            binding.a2Tran.visibility = View.GONE
            binding.a2.isClickable = true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        getTlCountDownTimer?.cancel()
        getTlShowBtnCountDownTimer?.cancel()
        getTlCountDownTimer = null
        getTlShowBtnCountDownTimer = null
        job?.cancel()
        scope?.cancel()
        job = null
        scope = null
    }

    private fun loadAd() {
        if (mRewardVideoAd == null) {
            mRewardVideoAd = ATRewardVideoAd(context, "b68400aae18fc0")
        }
        val userid = UserInfoSpUtils().getUserInfo().userId
        val userdata = UserInfoSpUtils().getUserInfo().nickName
        val localMap: MutableMap<String, Any> = HashMap()
        localMap[ATAdConst.KEY.USER_ID] = userid
        localMap[ATAdConst.KEY.USER_CUSTOM_DATA] = userdata
        mRewardVideoAd?.setLocalExtra(localMap)
        mRewardVideoAd?.setAdListener(this)
        mRewardVideoAd?.load()
    }

    private var isReload = false

    private fun showAd() {
        if (mRewardVideoAd?.isAdReady == true) {
            mRewardVideoAd?.show(activity)
            return
        }

        // 在 Fragment 中使用
        if (isAdded && activity != null && !requireActivity().isFinishing) {
            loadDialog = LoadingDialog(activity)
            loadDialog?.show()
            startReloadRewardVideoAd()
            startReloadRewardVideoAd?.start()
        }
        isReload = true
        if (mRewardVideoAd?.checkAdStatus()?.isLoading != true) mRewardVideoAd?.load()

    }

    private var isRewardedVideoFinish = false

    override fun onRewardedVideoAdLoaded() {
        LogUtils.e("DFDFDF=onRewardedVideoAdLoaded")
        startReloadRewardVideoAd?.cancel()
        startReloadRewardVideoAd = null
        if (loadDialog?.isShowing == true) loadDialog?.dismiss()
        if (isReload) showAd()
    }

    override fun onRewardedVideoAdFailed(p0: AdError?) {
        LogUtils.e("DFDFDF=onRewardedVideoAdFailed${p0?.code}")
    }

    override fun onRewardedVideoAdPlayStart(p0: ATAdInfo?) {
        isReload = false
        isRewardedVideoFinish = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val current = LocalDateTime.now()
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            startAdTime = current.format(formatter)
        } else {
            startAdTime = DateTimeUtils.getCurrentDateTime()
        }

        mRewardVideoAd?.load()
        LogUtils.e("DFDFDF=onRewardedVideoAdPlayStart${p0.toString()}")
    }

    override fun onRewardedVideoAdPlayEnd(p0: ATAdInfo?) {
        LogUtils.e("DFDFDF=onRewardedVideoAdPlayEnd${p0.toString()}")
        isRewardedVideoFinish = true
    }

    override fun onRewardedVideoAdPlayFailed(p0: AdError?, p1: ATAdInfo?) {
        LogUtils.e("DFDFDF=onRewardedVideoAdPlayFailed${p0?.code}===${p1.toString()}")
    }

    override fun onRewardedVideoAdClosed(p0: ATAdInfo?) {
        LogUtils.e("DFDFDF=onRewardedVideoAdClosed${p0.toString()}")
        if (!isRewardedVideoFinish) {
            ToastUtils.showShort("请观看完广告再关闭！")
        }
    }

    override fun onRewardedVideoAdPlayClicked(p0: ATAdInfo?) {
        LogUtils.e("DFDFDF=onRewardedVideoAdPlayClicked${p0.toString()}")
    }

    override fun onReward(p0: ATAdInfo?) {

        LogUtils.e("DFDFDF=onReward${p0.toString()}")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val current = LocalDateTime.now()
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            endAdTime = current.format(formatter)
        } else {
            endAdTime = DateTimeUtils.getCurrentDateTime()
        }

        saveRecord(p0)
    }

    private fun saveRecord(p0: ATAdInfo?) {

        if (p0 == null) return
        val map = HashMap<String, Any>()
        map["adSourceId"] = p0.adsourceId.toInt()
        map["beginTime"] = startAdTime.toString()
        map["finishTime"] = endAdTime.toString()
        map["networkFormId"] = p0.networkFirmId
        map["networkName"] = p0.networkName
        map["networkPlacementId"] = p0.networkPlacementId
        map["nickName"] = UserInfoSpUtils().getNickName()
        map["placementId"] = p0.placementId
        map["recordId"] = p0.requestId
        map["revenue"] = p0.publisherRevenue.toDouble()
        map["userId"] = UserInfoSpUtils().getUserId()
        map["ecpm"] = p0.ecpm.toString()
        map["adSourceIndex"] = p0.adsourceIndex
        map["adSourceType"] = p0.adSourceAdType
        map["resultJson"] = p0.toString()

        val body = BaseRetrofit.getRequestBodyByMapToJson(map)

        BaseRetrofit.getInstance().apiService.saveRecord(body).enqueue(object : Callback2<Any>() {
            override fun success(body: Any?) {
                addPower()
                LogUtils.e("dfdfdfdf广告同步成功！")
            }

            override fun fail(msg: String?) {
                ToastUtils.showShort(msg)
            }
        })
    }

    private fun loadNativeAd() {
        if (atNative == null) {
            atNative = ATNative(context, "b68400acd7390c", object : ATNativeNetworkListener {
                override fun onNativeAdLoaded() {
                    val nativeAd: NativeAd? = atNative?.getNativeAd(getATShowConfig())
                    try {
                        nativeAd?.renderAdContainer(binding.fragmentDatiContentAd, null)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                override fun onNativeAdLoadFail(adError: AdError) {
                    LogUtils.e("onNativeAdLoadFail:" + adError.fullErrorInfo)
                    atNative = null
                    loadNativeAd()
                }
            })
        }
        binding.fragmentDatiContentAd.removeAllViews()
        atNative?.makeAdRequest()
    }

    private fun loadInterstitial() {

        interstitialAd = ATInterstitial(context, "b68400ac31936e")
        interstitialAd?.setNativeAdCustomRender { mixNativeAd, atAdInfo ->
            MediationNativeAdUtil.getViewFromNativeAd(
                context,
                mixNativeAd,
                atAdInfo,
                true
            )
        }
        interstitialAd?.setAdListener(object : ATInterstitialListener {
            override fun onInterstitialAdLoaded() {
                LogUtils.e("==========onInterstitialAdLoaded")
            }

            override fun onInterstitialAdLoadFail(p0: AdError?) {
                LogUtils.e("===========onInterstitialAdLoadFail")
            }

            override fun onInterstitialAdClicked(p0: ATAdInfo?) {
                LogUtils.e("===========onInterstitialAdClicked")
            }

            override fun onInterstitialAdShow(p0: ATAdInfo?) {
                LogUtils.e("=============onInterstitialAdShow")
            }

            override fun onInterstitialAdClose(p0: ATAdInfo?) {
                initInAdTime()
            }

            override fun onInterstitialAdVideoStart(p0: ATAdInfo?) {
                interstitialAd?.load()
                LogUtils.e("===========onInterstitialAdVideoStart")
            }

            override fun onInterstitialAdVideoEnd(p0: ATAdInfo?) {
                LogUtils.e("==============onInterstitialAdVideoEnd")
            }

            override fun onInterstitialAdVideoError(p0: AdError?) {
                LogUtils.e("==========onInterstitialAdVideoError")
            }

        })
        interstitialAd?.load()

    }

    private fun loadBannerAd() {
        val mBannerView = ATBannerView(context)
        mBannerView.setPlacementId("b68400aba2a385")
        mBannerView.setShowConfig(getATShowConfig())
        mBannerView.setBannerAdListener(this)
        binding.fragmentDatiBanner.removeAllViews()
        binding.fragmentDatiBanner.addView(mBannerView)
        mBannerView.loadAd()
    }

    private fun getATShowConfig(): ATShowConfig {
        val builder: ATShowConfig.Builder = ATShowConfig.Builder()
        builder.scenarioId("banner_ad_show_1")
        builder.showCustomExt("banner_ad_show_custom_ext")

        return builder.build()
    }

    private fun getATShowConfig1(): ATShowConfig {
        val builder = ATShowConfig.Builder()
        builder.scenarioId("interstitial_ad_show_1")
        builder.showCustomExt("interstitial_ad_show_custom_ext")

        return builder.build()
    }

    override fun onBannerLoaded() {
        LogUtils.e("dfdfdf onBannerLoaded")
    }

    override fun onBannerFailed(p0: AdError?) {
        LogUtils.e("dfdfdf onBannerFailed")
    }

    override fun onBannerClicked(p0: ATAdInfo?) {
        LogUtils.e("dfdfdf onBannerClicked")
    }

    override fun onBannerShow(p0: ATAdInfo?) {
        LogUtils.e("dfdfdf onBannerShow")
    }

    override fun onBannerClose(p0: ATAdInfo?) {
        LogUtils.e("dfdfdf onBannerClose")
    }

    override fun onBannerAutoRefreshed(p0: ATAdInfo?) {
        LogUtils.e("dfdfdf onBannerAutoRefreshed")
    }

    override fun onBannerAutoRefreshFail(p0: AdError?) {
        LogUtils.e("dfdfdf onBannerAutoRefreshFail")
    }
}