package com.ym.game.view

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.ColorDrawable
import android.view.*
import android.view.animation.AnimationUtils
import android.widget.*
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ym.library.listener.OnRecycleItemClickListener
import com.ym.game.listener.IDialogViewCloseCallback
import com.ym.game.adapter.SigninDropsAdapter
import com.ym.game.adapter.WateringTaskAdpater
import com.ym.game.adapter.WelfareDiamondAdapter
import com.ym.game.adapter.WelfareTaskAdpater
import com.ym.game.contract.WelfareContract
import com.ym.game.presenter.WateringRewardPresenter
import com.ym.game.presenter.WelfarePresenter
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.Subscribe
import com.ym.library.rxbus.ThreadMode
import com.ym.xynt.R
import com.ym.library.listener.IAdVideoListener
import com.ym.library.module.*
import com.ym.library.utils.*
import kotlinx.android.synthetic.main.activity_welfare.*

class WelfarePopupwindow : PopupWindow(), WelfareContract.View,
    OnRecycleItemClickListener<NewsEntity> {
    private val TAG = "WelfarePopupwindow"
    private var mListener: IDialogViewCloseCallback? = null
    private var view: View? = null
    private var mContext: Activity? = null
    private var mPresenter: WelfarePresenter? = null
    private var diamonAdapter: WelfareDiamondAdapter? = null
    private var taskAdapter: WelfareTaskAdpater? = null

    private var mDiamonList: MutableList<DiamondEntity> = ArrayList()
    private var mData: NewsEntity? = null
    private var mDiamondEntity: DiamondEntity? = null
    private var isClick = false


    fun init(mContext: Activity?, mListener: IDialogViewCloseCallback) {
        this.mListener = mListener
        this.mContext = mContext
        if (mContext == null) {
            return
        }
        if (mContext.isFinishing) {
            return
        }
        view = LayoutInflater.from(mContext).inflate(R.layout.layout_popup_welfare, null)
        EventUtils.onEvent("fuli_show", "福利弹窗曝光")
        init(view)
        initView()



        showAtLocation(
            view,
            Gravity.CENTER,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
    }

    var iv_welfare_reward_red_pg: TextView? = null
    var iv_welfare_reward_box: ImageView? = null
    var recycler_welfare_task: RecyclerView? = null
    var tv_welfare_diamond_progress: TextView? = null
    var progess_watering_bar: ProgressBar? = null
    var tv_welfare_diamond_conut: TextView? = null

    private fun initView() {
        view?.findViewById<ImageView>(R.id.iv_popup_close_fl)?.setOnClickListener { dismiss() }

        iv_welfare_reward_red_pg = view?.findViewById<TextView>(R.id.iv_welfare_reward_red_pg)
        iv_welfare_reward_box = view?.findViewById<ImageView>(R.id.iv_welfare_reward_box)
        recycler_welfare_task = view?.findViewById<RecyclerView>(R.id.recycler_welfare_task)
        tv_welfare_diamond_progress = view?.findViewById<TextView>(R.id.tv_welfare_diamond_progress)
        progess_watering_bar = view?.findViewById<ProgressBar>(R.id.progess_watering_bar)
        tv_welfare_diamond_conut = view?.findViewById<TextView>(R.id.tv_welfare_diamond_conut)



        EventUtils.onEvent("fuli_show")
        mPresenter = WelfarePresenter(this)


        iv_welfare_reward_box?.setOnClickListener {
            EventUtils.onEvent("welfare_task_reward_box_click")
            if (mDiamondEntity?.coins != null && mDiamondEntity?.max != null) {
                if (mDiamondEntity?.coins!! >= mDiamondEntity?.max!!) {
                    mPresenter?.getWelfareTaskBox()
                } else {
                    var lack = mDiamondEntity?.max!! - mDiamondEntity?.coins!!
                    MainDialog?.showWithDraw(
                        mContext,
                        3,
                        "",
                        "需要钻石${mDiamondEntity?.max}颗，还差${lack}颗，快去做任务领钻石吧",
                        "",
                        0,
                        null,
                        0,
                        null,
                        true,
                        Dialog(mContext as Context)
                    )
                }

            }

        }

        iv_welfare_reward_red_pg?.setOnClickListener {
            EventUtils.onEvent("welfare_task_reward_red_package_click")
            mPresenter?.getWelfareTaskCash()
        }

        taskAdapter = WelfareTaskAdpater(mContext, this)
        recycler_welfare_task?.layoutManager = LinearLayoutManager(mContext)
        recycler_welfare_task?.adapter = taskAdapter

        request()
    }

    private fun request() {
        mPresenter?.getDiamondList()
        mPresenter?.getTaskList()
    }

    override fun diamondListResult(result: DiamondEntity?) {
        if (result != null) {
            mDiamondEntity = result
            mDiamonList.clear()
            tv_welfare_diamond_progress?.text = "${result?.coins}/${result?.max}"
            progess_watering_bar?.max = result?.max ?: 10
            progess_watering_bar?.progress = result?.coins ?: 0

            if (result?.display != null && result?.display == 1) {
                tv_welfare_diamond_conut?.text = "集齐${result?.max}颗钻石可开宝箱"
                iv_welfare_reward_red_pg?.visibility = View.GONE
                iv_welfare_reward_box?.visibility = View.VISIBLE

//                clearAnimation()
                if (result?.coins != null && result?.max != null && result?.coins!! >= result?.max!!) {
                    iv_welfare_reward_box?.setImageResource(R.drawable.icon_welfare_box_open)
                    val oa: ObjectAnimator = ObjectAnimator.ofFloat(
                        iv_welfare_reward_box,
                        View.ROTATION,
                        0F, 30F, -25F, 0F, 0F, 0F, 0F, 0F, 0F
                    )
                    oa.repeatCount = ValueAnimator.INFINITE
                    oa.setDuration(2000).start()
                } else {
                    iv_welfare_reward_box?.animation =
                        AnimationUtils.loadAnimation(mContext, R.anim.scale_anim)
                    iv_welfare_reward_box?.setImageResource(R.drawable.icon_welfare_box_close)
                }
            } else {
                iv_welfare_reward_red_pg?.visibility = View.VISIBLE
                iv_welfare_reward_box?.visibility = View.GONE
                tv_welfare_diamond_conut?.text = "集齐${result?.max}颗钻石可提现"
//                iv_welfare_reward_red_pg?.animation =
//                    AnimationUtils.loadAnimation(mContext, R.anim.scale_anim)

            }
        }
    }

    override fun taskListResult(result: TaskListEntity?) {
        if (result != null) {
            taskAdapter?.clear()
            taskAdapter?.appendToList(result?.userTask!!)
            taskAdapter?.notifyDataSetChanged()
        }
    }

    override fun taskReceiveListResult(result: TaskCompleteEntity?) {
        request()
        if (result != null) {
            EventUtils.onEvent("welfare_task_receive_dialog_show")

            CenterDialog.showgetWaterDrop(
                mContext,
                3,
                mData?.coins?.toInt()!!,
                "welfare_task_receive",
                DialogInterface.OnCancelListener {

                },
                null
            )
        }
    }

    override fun taskCashResult(result: List<FlyBoxEntity>?) {
        if (result != null && result.isNotEmpty()) {
            mPresenter?.getDiamondList()
            MainDialog.showWelfareOpenBox(mContext, result, object : IDialogViewCloseCallback {
                override fun onCloseViewSuccess(isSuccess: Boolean) {

                }
            })
        }
    }

    override fun welfareTaskCashResult(result: ExchangeEntity?) {
        if (result != null) {
            mPresenter?.getDiamondList()
            MainDialog?.showWithDraw(
                mContext,
                result?.status ?: 0,
                result?.title ?: "",
                result?.reason ?: "",
                result?.buttonText ?: "",
                result?.buttonStatus ?: 0,
                null,
                7,
                null,
                true,
                Dialog(mContext as Context)
            )
        }
    }

    override fun taskTimeCd(time: Int?) {
        if (time == 0 && mSid != null && mSid != 0) {
            showAd(mSid!!)
        } else {
            Utils.showToast(mContext, "手速太快啦，${time}秒后再来吧")
        }
    }

    private var mSid: Int? = 0
    override fun onItemClick(view: View, position: Int, data: NewsEntity) {
        mData = data
        if (!isClick) {
            isClick = true
            //0未完成 1已领取 2可领取
            when (data.status) {
                0 -> {
                    EventUtils.onEvent("fuli_go_click_${data.sid}")
                    if (data.opentype == NewsEntity.AD_TYPE_SDK) {
                        if (data.sid != null) {

                            mSid = data.sid
//                            showAd(data.sid)
                            mPresenter?.getADShowTimer()
                            EventUtils.onEvent("welfare_task_undone_click_total")
                        }
                    } else {
                        JumpUtils.adJump(data, mContext)
                    }
                }
                1 -> {
                    Utils.showToast(mContext, "已领取")
                }
                2 -> {
                    if (data.opentype == NewsEntity.AD_TYPE_SDK) {
                        EventUtils.onEvent("welfare_task_done_click_total")
                    }
                    EventUtils.onEvent("fuli_done_click_${data.sid}")
                    mPresenter?.getTaskReceiveList(data?.sid)
                }
            }
            view?.postDelayed({
                isClick = false
            }, 1000)
        }

    }

    fun showAd(sId: Int) {
        AdUtils.playRewardAd(mContext as Activity, "WELFARE_TASK", object : IAdVideoListener {
            override fun onAdClose() {
                mPresenter?.getWelfareVideoReport(sId)
            }

            override fun onError(errorMsg: String?) {

            }
        })
    }

//    private fun clearAnimation() {
//        iv_welfare_reward_box?.clearAnimation()
//        iv_welfare_reward_red_pg?.clearAnimation()
//    }

    override fun dismiss() {
        mListener?.onCloseViewSuccess(true)
//        clearAnimation()
        taskAdapter?.clearAnimation()
        super.dismiss()
        LogUtils.i(TAG, "dismiss")
    }

    private fun init(view: View?) {
        // 设置外部可点击
        this.isOutsideTouchable = true
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        view?.setOnTouchListener(object : View.OnTouchListener {
            @SuppressLint("ClickableViewAccessibility")
            override fun onTouch(p0: View?, event: MotionEvent?): Boolean {
                val height = view?.findViewById<RelativeLayout>(R.id.layout_drops_root)?.getTop()
                val y = event?.getY()?.toInt()
                if (event?.getAction() === MotionEvent.ACTION_UP) {
                    if (y != null) {
                        if (height != null && y < height) {
                            dismiss()
                        }
                    }
                }
                return true
            }

        })
        /* 设置弹出窗口特征 */ // 设置视图
        this.contentView = view
        // 设置弹出窗体的宽和高
        this.height = RelativeLayout.LayoutParams.MATCH_PARENT
        this.width = RelativeLayout.LayoutParams.MATCH_PARENT
        // 设置弹出窗体可点击
        this.isFocusable = true
        // 实例化一个ColorDrawable颜色为半透明
        val dw = ColorDrawable(-0x60000000)
        // 设置弹出窗体的背景
        setBackgroundDrawable(dw)
        // 设置弹出窗体显示时的动画，从底部向上弹出
        this.animationStyle = R.style.main_photo_anim
        isClippingEnabled = false
    }

}