package com.duben.microtribe.ui.widgets

import android.app.Activity
import android.app.Dialog
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import com.duben.microtribe.R
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.utils.MilliCountDownTimer
import kotlinx.android.synthetic.main.dialog_vip_pay_cancel.*

class VipPayCancelDialog(
    val activity: Activity,
    val cash: Double,
    private val listener: DialogListener
) :
    Dialog(activity, R.style.dialog) {

    private var milliCountDownTimer: MilliCountDownTimer? = null

    private val lp: WindowManager.LayoutParams

    init {
        setContentView(R.layout.dialog_vip_pay_cancel)
        // 设置window属性
        lp = window!!.attributes
        lp.gravity = Gravity.CENTER
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.windowAnimations = R.style.DialogAnimFade
        window!!.attributes = lp

        // 设置外部不可关闭
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        setOnKeyListener { dialogInterface, i, keyEvent ->
            i == KeyEvent.KEYCODE_BACK
        }

        findViewById<View>(R.id.iv_back).setOnClickListener {
            dismiss()
        }
        tv_cancel_cash.text="${cash}元"
        listener.setDialog(this)
        findViewById<View>(R.id.btn).setOnClickListener(listener)

        milliCountDownTimer =
            MilliCountDownTimer(getShowTime(), findViewById(R.id.tv_count_down))
        milliCountDownTimer?.start()
    }

    override fun dismiss() {
        if (activity.isFinishing) return
        super.dismiss()
        milliCountDownTimer?.cancel()
        milliCountDownTimer = null
    }

    /**
     * 获取倒计时时间
     */
    fun getShowTime(): Long {
        var showTime = 0L
        val currentTime = System.currentTimeMillis()
        val diff = (currentTime - AppConfig.splashTime) / 1000 / 60 //获取两个时间相差的分钟
        if (diff < 60) {
            showTime = 60 - diff
        } else {
            showTime = 59
            AppConfig.splashTime = currentTime
        }
        return showTime * 60 * 1000
    }

}