package com.ym.game.view

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.drawable.ColorDrawable
import android.view.*
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
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.contract.WateringRewardContract
import com.ym.game.presenter.WateringRewardPresenter
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.RxBusUtil
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.*

/**
 *Craeted by ${junqi.li}
 *Craeted by 2020/9/12
 *  每日水滴
 */
class SiginDropsPopupwindow : PopupWindow(), WateringRewardContract.View,
    OnRecycleItemClickListener<NewsEntity> {
    private val TAG = "Popupwindow"
    private var mListener: IDialogViewCloseCallback? = null
    private var view: View? = null
    private var mContext: Activity? = null
    private var tvPopupSigninDrops: TextView? = null
    private var mPresenter: WateringRewardPresenter? = null

    private var singinDropsAdapter: SigninDropsAdapter? = null
    private var wateringTaskAdpater: WateringTaskAdpater? = null
    var tv_tomAwardNum:TextView?=null
    fun init(mContext: Activity?, mListener: IDialogViewCloseCallback) {
        this.mListener = mListener
        this.mContext = mContext
        if (mContext==null){
            return
        }
        if (mContext.isFinishing){
            return
        }
//        ToponManager.initNativeAd((mContext as Activity), AdID.AD_DAILY_DRIP_BIGIMAGE)
//        ToponManager.initNativeAd((mContext as Activity), AdID.AD_LUCKY_DAILY_WATER_VIDEO)
//        ToponManager.initRewardAd((mContext as Activity), AdID.AD_LUCKY_WATER_HIGH_VIDEO)
        RxBusUtil.getDefault().register(this)
        mPresenter = WateringRewardPresenter(this)
        view = LayoutInflater.from(mContext).inflate(R.layout.layout_popup_drops, null)
        EventUtils.onEvent("renwu_show", "任务弹窗曝光")
        init(view)
        initView()
//        mPresenter?.getOrchardSignTask()
        mPresenter?.getRrchardDailyTask()
        showAtLocation(
            view,
            Gravity.CENTER,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
    }

    private fun initView() {

        tvPopupSigninDrops = view?.findViewById<TextView>(R.id.tv_popup_signin_drops)
        tv_tomAwardNum=view?.findViewById(R.id.id_tv_reward_coin)
        val recyclerSigninDrops =
            view?.findViewById<RecyclerView>(R.id.recycler_popup_signin_drops)
        val recyclerWatering =
            view?.findViewById<RecyclerView>(R.id.recycler_popup_watering)

        view?.findViewById<ImageView>(R.id.iv_popup_close)?.setOnClickListener { dismiss() }

        singinDropsAdapter = SigninDropsAdapter(mContext)
        recyclerSigninDrops?.layoutManager =
            GridLayoutManager(mContext,7)
//        recyclerSigninDrops?.layoutManager = CardLayoutManager()
        recyclerSigninDrops?.adapter = singinDropsAdapter

        wateringTaskAdpater = WateringTaskAdpater(mContext, 1, this)
        recyclerWatering?.adapter = wateringTaskAdpater
    }


    @SuppressLint()
    @Subscribe(code = RxBusConstant.RX_MAIN_WATER_DROP_UPDATE, threadMode = ThreadMode.MAIN)
    fun updateList() {

        mPresenter?.getRrchardDailyTask()
    }

    override fun onItemClick(view: View, position: Int, data: NewsEntity) {
        // 0未完成 1已领取 2可领取
        when (data.status) {
            0 -> {

                // 跳转页面 1转盘 2高额水滴任务 3首页 4激励视频 直客任务链接"
                // if()
                //  appmodel_id
                // 应用类模块跳转 跳转到幸运农田首页 65
                //应用类模块跳转到幸运农田转盘抽奖 63
                //应用类模块跳转到幸运农田开宝箱 64
                //应用类模块跳转到幸运农田福利中心 66
                if (data.opentype == 7) {
                    if (data.appmodel_id == 65) {
                        dismiss()
                    } else if (data.appmodel_id == 63) {
                        dismiss()
                        TurntableDialog.showTurntable(mContext, mListener!!)
                    } else if (data.appmodel_id == 64) {
                        dismiss()
                    } else if (data.appmodel_id == 66) {
                        dismiss()
                        JumpUtils.jumpWelfareActivity()
                    }
                } else if (data.opentype == 1) {
                    if (data.sid != null) {
                       // EventUtils.onEvent("welfare_task_undone_click", "${data.sid}")
                        showAd(data.sid)
                        EventUtils.onEvent("renwu_undone_click_total")
                    }
                 else {
                    JumpUtils.adJump(data, mContext)
                }

                }else if(data.opentype==2){
                    dismiss()
                    //直客链接
                    JumpUtils.adJump(data, (mContext as Activity))
                }

//                when (data.opentype) {
//
//                    1 -> {
//
//                    }
//                    2 -> {
//                        dismiss()
//                        // WateringTaskPopupwindow().init(mContext)
//                    }
//                    3 -> dismiss()
//                    6 -> {
//
////                        JumpUtils.h5Jump(
////                            "每日福利",
////                            Constant.Param.WelfareCenter,
////                            false,
////                            mContext as Activity
////                        )
//                    }
//                    4 -> {
//                        EventUtils.onEvent("click_receive_coin_task_video_btn", "领金币任务视频")
//
//                        AdUtils.playRewardAd((mContext as Activity),"receive_coin_task",object : IAdVideoListener {
//                            override fun onAdClose() {
//
//                            }
//
//                            override fun onError(errorMsg: String?) {
//
//                            }
//                        })
//                    }
//
//                }
            }
        }
    }
fun showAd(sId: Int) {
    AdUtils.playRewardAd(mContext as Activity, "home_task", object : IAdVideoListener {
        override fun onAdClose() {
           // mPresenter?.getTaskComplete(sId)
          wateringTaskAdpater?.getDripTaskReceive(1,sId)
        }

        override fun onError(errorMsg: String?) {

        }
    })
}


    //签到
    override fun rchardSignTaskResult(data: SinginEntity) {
        LogUtils.i(TAG, "签到")
        if (data != null) {
            // var content = "连续签到7天，领惊喜大奖"
            // tvPopupSigninDrops?.text = content
            singinDropsAdapter?.clear()
            singinDropsAdapter?.appendToList(data.signInfoList)
            singinDropsAdapter?.notifyDataSetChanged()
            tv_tomAwardNum?.text=" ${data.tomAwardNum} "
            if (data.isPop == 1) {
                //首次签到弹窗
                MainDialog.showgetWaterDrop(mContext, 4, "singin", data.awardNum, null)
                RxBusUtil.getDefault().send(RxBusConstant.RX_MAIN_TURNTABLE_LOTTERYED)
            }
        }

    }

    override fun taskListResult(result: TaskListEntity?) {
        //wateringTaskAdpater?.clearAnimation()
        wateringTaskAdpater?.clear()
        wateringTaskAdpater?.appendToList(result?.userTask)
        wateringTaskAdpater?.notifyDataSetChanged()
    }

    //每日水滴任务列表
    override fun rchardDailyTaskResult(datas: List<WateringTaskEntity>) {

//        wateringTaskAdpater?.clear()
//        wateringTaskAdpater?.appendToList(datas)
//        wateringTaskAdpater?.notifyDataSetChanged()
    }

    override fun dismiss() {
        mListener?.onCloseViewSuccess(true)
        super.dismiss()
        RxBusUtil.getDefault().unregister(this)
        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
    }
}