package com.ym.library.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Build
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.ym.admodule.config.AdManager
import com.ym.admodule.config.ZXADSizeConfig
import com.ym.library.Constant
import com.ym.library.R
import com.ym.library.base.BaseDialog
import com.ym.library.listener.AdCallback

/**
 * Created by gaoleichao on 2018/8/17.
 */
object CenterDialog : BaseDialog() {


    fun showDialogUpdateVersion(
        activity: Activity?,
        title: String,
        desc: String,
        isCancel: Boolean,
        isShowLoginDialog: Boolean,
        listener: View.OnClickListener,
        adCallback: AdCallback<Int>?
    ) {
        if (activity == null) {
            return
        }
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView = showBottomDialog(
            R.layout.dialog_update_viersion,
            activity,
            mDialog,
            0,
            Gravity.CENTER
        )
        if (isCancel) {
            mDialog.setCanceledOnTouchOutside(true)
            mDialog.setOnDismissListener {
                SettingPreference.setCancelUpdateDate(activity, Utils.getNowDate())
                Constant.Switch.isShowUpdateDialoging = false
                if (isShowLoginDialog) {
                    adCallback?.onResult(0, 0)
                }
            }
        } else {
            mDialog.setCanceledOnTouchOutside(true)
        }
        mDialog.findViewById<ImageView>(R.id.id_close_update_dailog)
            .setOnClickListener(View.OnClickListener {
                mDialog?.dismiss()
            })
        mDialogView.findViewById<TextView>(R.id.tv_check_version_desc).text = desc
        mDialogView.findViewById<TextView>(R.id.btn_update_start).setOnClickListener {
            listener.onClick(it)
        }
        mDialog?.show()
    }

    /**
     * 获得微信红包
     */
    fun showGuideGetMoney(activity: Activity?,title:String, cashStr: String, webView: WebView?) {
        if (activity == null) {
            return
        }
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme75)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_lib_get_money,
                activity,
                mDialog,
                0,
                Gravity.CENTER
            )
        val tv_money = mDialogView?.findViewById<TextView>(R.id.id_tv_cash_content)
        val tvTitle = mDialogView?.findViewById<TextView>(R.id.id_tv_title)
        tv_money.text = "恭喜您成功兑换${cashStr}元红包，您可以前往微信钱包查看到账情况"
        tvTitle.text = title

        mDialogView.findViewById<TextView>(R.id.id_tv_go_on_make_money).setOnClickListener {
             webView?.loadUrl("javascript:onResume()")
            mDialog.dismiss()
        }
        mDialogView.findViewById<ImageView>(R.id.id_img_dialog_close).setOnClickListener {
            webView?.loadUrl("javascript:onResume()")
            mDialog.dismiss()
        }

        mDialog.setCanceledOnTouchOutside(false)
        mDialog.setCancelable(false)
        mDialog.show()
    }

//    /**
//     * 领取红包奖励
//     */
//    fun getRewardDialog(
//        activity: Activity,
//        reward: DialogRewardEntity,
//        btnStr: String,
//        withdrawClick: View.OnClickListener,
//        comePage: String
//    ) {
//        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
//        val mDialogView =
//            CenterDialog.showBottomDialog(
//                R.layout.dialog_datecoins,
//                activity,
//                mDialog,
//                0,
//                Gravity.CENTER
//            )
//        val tv_time = mDialogView.findViewById<TextView>(R.id.id_tv_dialog_datecoins_time)
//        val img_close = mDialogView.findViewById<ImageView>(R.id.id_dialog_datecoins_close)
//        val idAdLayout = mDialogView.findViewById<FrameLayout>(R.id.id_dialog_result_ad_layout)
//        tv_time.visibility = View.VISIBLE
//        img_close.visibility = View.GONE
//
//        ToponManager.loadNative(activity,idAdLayout,object :ToponNativeListener {
//            override fun onAdImpressed(atAdInf: ATAdInfo) {
//                EventUtils.onEvent(
//                    "ad_show",
//                    Utils.obj2Str(AdEntity(atAdInf.adNetworkType, AdID.mPlacementId_open_rp_bigimage, "打开红包大图"))
//                )
//            }
//
//            override fun onAdClicked(atAdInf: ATAdInfo, view: ATNativeAdView) {
//                EventUtils.onEvent(
//                    "ad_click",
//                    Utils.obj2Str(AdEntity(atAdInf.adNetworkType, AdID.mPlacementId_open_rp_bigimage, "打开红包大图"))
//                )
//            }
//
//            override fun onAdVideoStart() {
//            }
//
//            override fun onAdVideoEnd() {
//            }
//
//        },AdID.mPlacementId_open_rp_bigimage)
//
//        img_close.setOnClickListener {
//            mDialog.dismiss()
//        }
//        mDialogView.findViewById<TextView>(R.id.id_dialog_datecoins_coin).text =
//            "+" + reward.double?.rewardCent + "金币"
//
//        if (btnStr.isEmpty()) {
//            mDialogView.findViewById<RelativeLayout>(R.id.id_rel_dialog_btn).visibility = View.GONE
//        } else {
//            mDialogView.findViewById<TextView>(R.id.id_tv_dialog_btn_desc).text = btnStr
//        }
//
//        mDialogView.findViewById<RelativeLayout>(R.id.id_rel_dialog_btn).setOnClickListener {
//            withdrawClick.onClick(it)
//            mDialog.dismiss()
//        }
//        mDialog?.setCanceledOnTouchOutside(false)
//        mDialog?.setCancelable(false)
//        mDialog.show()
//        countDown(3000, tv_time, img_close)
//    }
//
//    /**
//     * 任务领取红包奖励
//     */
//    fun getTaskRewardDialog(
//        activity: Activity,
//        reward: String,
//        btnStr: String,
//        withdrawClick: View.OnClickListener,
//        taskType: String
//    ) {
//        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
//        val mDialogView =
//            CenterDialog.showBottomDialog(
//                R.layout.dialog_datecoins2,
//                activity,
//                mDialog,
//                0,
//                Gravity.CENTER
//            )
//        val tv_time = mDialogView.findViewById<TextView>(R.id.id_tv_dialog_datecoins_time)
//        val img_close = mDialogView.findViewById<ImageView>(R.id.id_dialog_datecoins_close)
//        val layouAd = mDialogView.findViewById<FrameLayout>(R.id.id_dialog_result_ad_layout)
//
//        var adIdImg = ""
//        var adNameImg = ""
//        when (taskType) {
//            //闯关
//            "guessTask" -> {
//                adIdImg = AdID.mPlacementId_pass_complete2
//                adNameImg = "闯关任务完成大图"
//            }
//            //每日任务
//            "DailyTask" -> {
//                adIdImg = AdID.mPlacementId_daily_task_finish_bigimage
//                adNameImg = "每日任务完成大图"
//            }
//            //签到
//            "SignTask" -> {
//                adIdImg = AdID.mPlacementId_daily_task_time_period_signin_bigimag
//                adNameImg = "每日任务时段签到大图"
//            }
//        }
//
//        ToponManager.loadNative(
//            activity, layouAd,
//            object : ToponNativeListener {
//                override fun onAdImpressed(atAdInf: ATAdInfo) {
//                    EventUtils.onEvent(
//                        "ad_show",
//                        Utils.obj2Str(
//                            AdEntity(
//                                atAdInf.networkFirmId.toString(),
//                                adIdImg,
//                                adNameImg
//                            )
//                        )
//                    )
//                }
//
//                override fun onAdClicked(atAdInf: ATAdInfo, view: ATNativeAdView) {
//                    EventUtils.onEvent(
//                        "ad_click",
//                        Utils.obj2Str(
//                            AdEntity(
//                                atAdInf.networkFirmId.toString(),
//                                adIdImg,
//                                adNameImg
//                            )
//                        )
//                    )
//
//                }
//
//                override fun onAdVideoStart() {
//                }
//
//                override fun onAdVideoEnd() {
//                }
//
//            }
//            , adIdImg
//        )
//
//
//
//        tv_time?.visibility = View.VISIBLE
//        img_close?.visibility = View.GONE
//        img_close?.setOnClickListener {
//            when (taskType) {
//                "guessTask" -> {
//                    EventUtils?.onEvent("task_success_close_click", "完成任务直接领奖")
//                }
//                "DailyTask" -> {
//                    EventUtils?.onEvent("task_success_close_click", "完成任务直接领奖")
//                }
//                "SignTask" -> {
//
//                }
//            }
//            mDialog?.dismiss()
//        }
//        if (btnStr == "") {
//            mDialogView.findViewById<RelativeLayout>(R.id.id_rel_dialog_btn)?.visibility = View.GONE
//        } else {
//            mDialogView.findViewById<TextView>(R.id.id_tv_dialog_btn_desc)?.text = btnStr
//        }
//
//        mDialogView.findViewById<TextView>(R.id.id_dialog_datecoins_coin)?.text = reward
//
//        mDialogView.findViewById<RelativeLayout>(R.id.id_rel_dialog_btn)?.setOnClickListener {
//            if (Utils.isFastClick()) {
//                var adId = ""
//                var adName = ""
//                when (taskType) {
//                    //闯关
//                    "guessTask" -> {
//                        adId = AdID.mPlacementId_pass_complete
//                        adName = "闯关任务完成激励视频"
//                    }
//                    //每日任务
//                    "DailyTask" -> {
//                        adId = AdID.mPlacementId_daily_task_video
//                        adName = "每日任务激励视频"
//                    }
//                    //签到
//                    "SignTask" -> {
//                        adId = AdID.mPlacementId_daily_task_time_period_signin_video
//                        adName = "每日任务时段签到激励视频"
//                    }
//                }
//
//                ToponManager.loadReward(activity, object : ToponRewardListener {
//                    override fun onRewardedVideoAdPlayClicked(entity: ATAdInfo) {
//                        EventUtils.onEvent(
//                            "ad_click",
//                            Utils.obj2Str(
//                                AdEntity(
//                                    entity.networkFirmId.toString(),
//                                    adId,
//                                    adName
//                                )
//                            )
//                        )
//
//                    }
//
//                    override fun onRewardedVideoAdClosed(entity: ATAdInfo) {
//                        withdrawClick.onClick(mDialogView)
//                        mDialog?.dismiss()
//                    }
//
//                    override fun onRewardedVideoAdFailed(errorCode: AdError) {
//                        withdrawClick.onClick(mDialogView)
//                        mDialog?.dismiss()
//                    }
//
//                    override fun onRewardedVideoAdPlayEnd(entity: ATAdInfo) {
//                        EventUtils.onEvent("ad_ended", Utils.obj2Str(AdEntity("ad_ended", "ad_ended", adName)))
//                    }
//
//                    override fun onRewardedVideoAdPlayStart(entity: ATAdInfo) {
//                        EventUtils.onEvent(
//                            "ad_show",
//                            Utils.obj2Str(
//                                AdEntity(
//                                    entity.networkFirmId.toString(),
//                                    adId,
//                                    adName
//                                )
//                            )
//                        )
//                    }
//                }, adId)
//            }
//
//
//        }
//        mDialog?.setCanceledOnTouchOutside(false)
//        mDialog?.setCancelable(false)
//        mDialog?.show()
//        countDown(3000, tv_time, img_close)
//    }
    /**
     * 水滴发放
     * type:   1水滴   2金币
     * waterDropCount:   奖励数量
     * adType: 广告的类型
     */
    fun showgetWaterDrop(
        context: Activity?,
        type: Int,
        rewardCount: Int,
        actionName:String,
        listener: DialogInterface.OnCancelListener,
        mWebView: WebView?
    ) {
        if (context == null) {
            return
        }
        val mDialog = Dialog(context, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(
                R.layout.dialog_get_diamand,
                context,
                mDialog,
                0,
                Gravity.CENTER
            )
        val imgbg = mDialogView?.findViewById<ImageView>(R.id.iv_get_bg)
        if(type==3){
            imgbg.setImageResource(R.drawable.icon_diamand)
        }
        val tvGetDropCount = mDialogView?.findViewById<TextView>(R.id.tv_get_count)
        val layoutAd = mDialogView?.findViewById<FrameLayout>(R.id.layout_ad)
        tvGetDropCount.text = "+${rewardCount}"

        AdUtils.showFeedAd(context,actionName,layoutAd)

        mDialogView.findViewById<TextView>(R.id.btn_get_diamand).setOnClickListener {
//            mWebView?.loadUrl("javascript:onResume()")
            mDialog?.dismiss()
        }
        mDialogView.findViewById<ImageView>(R.id.lv_get_drop_close).setOnClickListener {
//            mWebView?.loadUrl("javascript:onResume()")
            mDialog?.dismiss()
        }

        mDialog?.setOnCancelListener {
            listener.onCancel(it)
            AdUtils.loadFeedCacheAdToCache(context)
        }

        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.setCancelable(false)
        mDialog?.show()
    }


    var coinsDialog: Dialog? = null

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    fun showNewCoinsDialog(context: Activity, rewardCoins: Int): Dialog? {
        coinsDialog = Dialog(context, R.style.CenterCompatDialogTheme)
        val mDialogView: View? =
            showBottomDialog(R.layout.dialog_coins, context, coinsDialog!!, 0, Gravity.CENTER)
        val mCoinsText: TextView = mDialogView!!.findViewById(R.id.id_dialog_coins_num)
        coinsDialog?.window?.setDimAmount(0f)

        mCoinsText.text = rewardCoins.toString()
        mCoinsText.postDelayed(Runnable {
            if (context == null || context.isDestroyed() || context.isFinishing()) {
                return@Runnable
            }
            coinsDialog?.dismiss()

        }, 2000)
        try {
            if (context != null && !context.isDestroyed() && !context.isFinishing()) {
                coinsDialog?.show()
            }
        } catch (e: Exception) {

        }

        return coinsDialog
    }

    fun showDialogReadCoins(
        activity: Activity?,
        coins: Int,
        value: String,
        onClickListener: View.OnClickListener
    ) {
        if (activity == null) {
            return
        }
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(R.layout.dialog_read_coins, activity, mDialog, 0, Gravity.CENTER)
        var closeImg = mDialogView.findViewById<ImageView>(R.id.id_dialog_read_coins_close)
        var mDesc = mDialogView.findViewById<TextView>(R.id.id_dialog_read_coins_desc)
        var mValue = mDialogView.findViewById<TextView>(R.id.id_dialog_read_coins_value)
        var mBtn = mDialogView.findViewById<TextView>(R.id.id_dialog_read_coins_btn)
        mValue?.text = "+" + coins + "金币"
        if (TextUtils.equals(value, "0")) {
            mDesc?.text = "恭喜您，任务达成"
            mBtn?.text = "立即提现"
        } else {
            mBtn?.text = "继续赚"
//            mDesc?.text = Html.fromHtml("再赚<font color=\"#FF6B6B\">${value}</font>金币即可提现")
        }
        closeImg?.setOnClickListener {
            mDialog?.dismiss()
        }
        mBtn.setOnClickListener {
            mDialog?.dismiss()
            if (TextUtils.equals(value, "0")) {
                mDialog?.dismiss()
                activity.finish()
                JumpUtils.withdrawCash()
                EventUtils.onEvent("kkz_go_withdraw_click")
            } else {
                EventUtils.onEvent("kkz_continue_click")
                onClickListener.onClick(it)
            }
        }

        mDialog?.setCancelable(false)
        mDialog?.show()
    }

    /**
     * 退出弹窗
     */
    fun showSignOutDialog(activity: Activity, callBack: View.OnClickListener) {
        if (activity == null) {
            return
        }
        Constant.isDialogActivity = 1
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView =
            showBottomDialog(R.layout.dialog_sign_out_layout, activity, mDialog, 0, Gravity.CENTER)
        val closeImg = mDialogView.findViewById<ImageView>(R.id.dialog_scratch_dialog_close_img)
        val btn = mDialogView.findViewById<TextView>(R.id.dialog_scratch_dialog_bg)
        val cancelBtn = mDialogView.findViewById<TextView>(R.id.dialog_scratch_dialog_cancel)

        closeImg?.setOnClickListener {
            mDialog?.dismiss()
        }

        btn?.setOnClickListener {
            mDialog?.dismiss()
        }
        cancelBtn?.setOnClickListener {
            callBack.onClick(it)
            activity?.finish()
        }
        mDialog?.setCancelable(false)
        mDialog?.show()
    }

    /**
     * 倒计时
     */
    fun countDown(time: Long, textView: TextView, img_close: ImageView) {
        var countDownTimer: CountDownTimer? = null
        //时间  倒计时   入参long类型
        countDownTimer = object : CountDownTimer(time, 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {
                textView.text = ((millisUntilFinished / 1000) + 1).toString() + "秒"
            }

            override fun onFinish() {
                countDownTimer?.cancel()
                countDownTimer = null
                textView.isEnabled = true
                textView.visibility = View.GONE
                img_close.visibility = View.VISIBLE
            }
        }
        countDownTimer?.start()
    }

    fun showPermission(
        activity: Activity,
        title: String,
        quitListener: View.OnClickListener,
        settingListener: View.OnClickListener
    ) {
        if (activity == null) {
            return
        }
        val mDialog = Dialog(activity, R.style.UpdateVersionCompatDialogTheme)
        val mDialogView = showBottomDialog(
            R.layout.dialog_permissisns,
            activity!!,
            mDialog,
            0,
            Gravity.CENTER
        )
        mDialogView.findViewById<TextView>(R.id.tv_info).text =
            "多多花园缺少必要权限：\n\n${title}\n请点击\"设置\"-\"权限\"-打开所需权限。\n最后点击两次后退按钮，即可返回。"

        mDialogView.findViewById<TextView>(R.id.btn_permission_quit).setOnClickListener {
            quitListener.onClick(it)
        }

        mDialogView.findViewById<TextView>(R.id.btn_permission_setting).setOnClickListener {
            settingListener.onClick(it)
            mDialog?.dismiss()
        }

        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.setCancelable(false)
        mDialog?.show()
    }

}