package com.ym.game.activity

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.text.Html
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.umeng.socialize.UMShareAPI
import com.ym.xynt.R
import com.ym.xynt.UserInfoEntity
import com.ym.game.adapter.WithdrawAdapter
import com.ym.game.view.MainDialog
import com.ym.library.listener.OnRecycleItemClickListener
import com.ym.library.module.BaseWithdrawEntity
import com.ym.library.module.WithdrawEntity
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.Subscribe
import com.ym.library.rxbus.ThreadMode
import com.ym.library.utils.*
import com.ym.library.utils.SettingPreference.getUserInfoData
import com.ym.modulecommon.base.BaseActivity
import com.ym.modulecommon.utils.AdPreference
import com.ym.userinfo.module.contract.UserContract
import com.ym.userinfo.module.entity.LotteryEntity
import com.ym.userinfo.module.presenter.UserPresenter
import kotlinx.android.synthetic.main.activity_user_info.*
import java.util.*

class UserInfoActivity : BaseActivity(), View.OnClickListener,
    OnRecycleItemClickListener<WithdrawEntity>, UserContract.View {
    override fun layoutID(): Int = R.layout.activity_user_info

    private var adapter: WithdrawAdapter? = null
    private var adapter2: WithdrawAdapter? = null

    //    private var withdrawListAdapter: WithdrawListAdapter? = null
    private var mData: WithdrawEntity? = null
    private var mData2: WithdrawEntity? = null

    private var mAdapterList: MutableList<WithdrawEntity> = ArrayList()
    private var mAdapterList2: MutableList<WithdrawEntity> = ArrayList()

    private var userData: UserInfoEntity? = null
    private var mLotteryEntity: LotteryEntity? = null
    private var mPresenter: UserPresenter? = null
    private var sessionId = ""

    // 提现机会倒计时
    private var remainTime = 0
    private val TAG = "UserInfoFragment"
    private var isRefresh = false

    //是否是抽奖提现
    private var isWithdrawLottery = false
    private var mRemainGuessNum = 0
    private var mWithdrawNum: Double? = 0.0


    override fun init() {
        EventUtils.onEvent("tixian_show")
        mPresenter = UserPresenter(this)
        initView()
        initData()
//        mPresenter?.requestUserGold()
        mPresenter?.requestUserMind()
        mPresenter?.requestWithdrawList()
        // mPresenter?.requestGuessMusicLottery()

//        request()
    }


    private fun initView() {

        val linearParams: LinearLayout.LayoutParams =
            id_rl_userinfo_toolbar.getLayoutParams() as LinearLayout.LayoutParams
        linearParams.height = StatusBarUtil.getStatusBarHeight(this) + Utils.dip2px(54)
        id_rl_userinfo_toolbar.setLayoutParams(linearParams)

        iv_user_setting.setOnClickListener(this)
        // btn_user_exchange_cash.setOnClickListener(this)
        btn_user_withdraw.setOnClickListener(this)
        tv_user_withdrawals_record.setOnClickListener(this)

        refresh_user_layout?.setColorSchemeResources(R.color.color_FCD974)
        refresh_user_layout?.setOnRefreshListener {
            isRefresh = true
            mPresenter?.requestWithdrawList()
        }

        iv_user_back.setOnClickListener {
            finish()
        }

         FilterUtils.addClickAlpha(btn_user_withdraw)
    }

    private fun initData() {
        adapter = WithdrawAdapter(this, this)
        recycler_user_withdraw.layoutManager =
            GridLayoutManager(this, 3) as RecyclerView.LayoutManager?
        recycler_user_withdraw.adapter = adapter
        //设置默认选择项
//        adapter?.setSelectPosition(0)

        adapter2 = WithdrawAdapter(this, object : OnRecycleItemClickListener<WithdrawEntity> {
            override fun onItemClick(view: View, position: Int, data: WithdrawEntity) {
                adapter2?.setSelectPosition(position)
                adapter2?.notifyDataSetChanged()
                setWirhdrawDescription2(data)
                id_tv_use_coin.text = "${data?.useCoin}"
            }
        })
        recycler_user_clockin_withdraw.layoutManager =
            GridLayoutManager(this, 3) as RecyclerView.LayoutManager?
        recycler_user_clockin_withdraw.adapter = adapter2
        //设置默认选择项
//        adapter2?.setSelectPosition(0)

    }

    private fun request() {
//        mPresenter?.requestUserGold()
        mPresenter?.requestWithdrawList()
      //  mPresenter?.requestGuessMusicLottery()
    }

    /**
     * 用户金币和抽奖列表配置
     */
    @SuppressLint()
    @Subscribe(code = RxBusConstant.RX_USER_LOTTERYED, threadMode = ThreadMode.MAIN)
    fun updateLotteryed() {
//        mPresenter?.requestUserGold()
     //   mPresenter?.requestGuessMusicLottery()
    }

    /**
     * 兑换金币
     */
    @SuppressLint()
    @Subscribe(code = RxBusConstant.RX_USER_COIN2CASH, threadMode = ThreadMode.MAIN)
    fun updateCoin2cash(sid: String) {
        mPresenter?.requestCoin2cash(sid)
    }

    override fun onItemClick(view: View, position: Int, data: WithdrawEntity) {
        mData = data
        mWithdrawNum = data?.cash
        id_tv_use_coin.text = "${data?.useCoin}"
        Log.d(TAG, "data?.cash:" + data?.cash)
        adapter?.setSelectPosition(position)
        adapter?.notifyDataSetChanged()

        setWirhdrawDescription(data)

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            // 设置
            R.id.iv_user_setting -> {
                EventUtils.onEvent("setting_click")
                JumpUtils.jumpSettingActivity()
            }
//            //兑换金币
//            R.id.btn_user_exchange_cash -> {
//                mPresenter?.requestCoin2cashCheck()
//            }
            //提现记录
            R.id.tv_user_withdrawals_record -> {
                JumpUtils.jumpWithdrawalsRecordActivity()
            }
            //立即提现
            R.id.btn_user_withdraw -> {
                if (Utils.isFastClick()) {
                    if (mWithdrawNum == 0.0) {
                        mWithdrawNum = 0.3
                    }
                    EventUtils.onEvent("tixian_btn_click", "立即提现按钮点击")
//                    mPresenter?.requestIsWxBind()
                    if (mData?.ifUse == 1 || mData2?.ifUse == 1) {
                        Toast.makeText(this@UserInfoActivity, "已提现", Toast.LENGTH_SHORT).show()
                    } else {
                        if (adapter?.getSelectPosition() != -1 && mData?.id != null) {
                            mPresenter?.requestWxWithdraw(mData?.id!!)
                        } else if (adapter2?.getSelectPosition() != -1 && mData2?.id != null) {
                            mPresenter?.requestWxWithdraw(mData2?.id!!)
                        } else {
                            Toast.makeText(this@UserInfoActivity, "请选择提现额度", Toast.LENGTH_SHORT)
                                .show()
                        }
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.i("WxImplUtils", "onActivityResult fragment")
        super.onActivityResult(requestCode, resultCode, data)
        try {
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        } catch (ex: Exception) {

        }
    }

    //常规提现配置
    override fun setWithdrawDataSuccess(datas: BaseWithdrawEntity?) {

        id_tv_coins.text = "${datas?.coins}"
        tv_user_cash_account.text = "约${datas?.cent}元"

        if (isRefresh) {
            refresh_user_layout?.isRefreshing = false
        }

        layout_user_withdraw.visibility = View.VISIBLE
        btn_user_withdraw.visibility = View.VISIBLE

        mAdapterList.clear()
        mAdapterList2.clear()
        for (data in datas?.wdList!!) {
            if (data?.type == 2) {
                mAdapterList2.add(data)
            } else {
                mAdapterList.add(data)
            }
        }

        if (adapter?.getSelectPosition() != -1) {
            mData = datas?.wdList!![adapter?.getSelectPosition()!!]
            setWirhdrawDescription(mAdapterList[adapter?.getSelectPosition()!!])
        }

        if (adapter2?.getSelectPosition() != -1) {
            mData2 = datas?.wdList!![adapter2?.getSelectPosition()!!]
            setWirhdrawDescription2(mAdapterList2[adapter2?.getSelectPosition()!!])
        }


        adapter?.clear()
        adapter?.appendToList(mAdapterList)
        adapter?.notifyDataSetChanged()

        adapter2?.clear()
        adapter2?.appendToList(mAdapterList2)
        adapter2?.notifyDataSetChanged()

    }

    override fun setWithdrawDataFailure() {
        layout_user_withdraw.visibility = View.GONE
        btn_user_withdraw.visibility = View.GONE
    }

    // 提现列表
    override fun setGuessMusicLotterySuccess(datas: List<LotteryEntity>) {
        if (datas.isNotEmpty()) {
            if (datas.size > 0) {
                mRemainGuessNum = datas[datas.size - 1].remainGuessNum
            }
        }
    }

    override fun setGuessMusicLotteryFailure() {
        recycler_withdraw_list.visibility = View.GONE
    }

    //转盘
    override fun setLotteryConfigSuccess(datas: List<WithdrawEntity>) {
//        UserDialog.showLotteryDialog(this, datas, sessionId, remainTime)
    }

    override fun setLotteryConfigFailure() {
    }

    override fun setUserGold(data: UserInfoEntity) {
        //        RxBusUtil.getDefault().send(RxBusConstant.RX_MAIN_ACTIVITY_TITLE, Constant.textInfo)
        if (data != null) {
            if (isRefresh) {
                refresh_user_layout?.isRefreshing = false
            }
            this.userData = data
            tv_user_cash_account.text = "${data.avaYuan}元"
//            tv_user_gold_conversionrate.text = "${data.coinRate}金币=1元"
//            tv_user_coin_account.text = "${data.avaCoin}"
        }
    }


    override fun setUserGoldFailure() {
        if (isRefresh) {
            refresh_user_layout?.isRefreshing = false
        }
    }


    //微信是否绑定
    override fun wxBindSuccess(data: UserInfoEntity) {
        if (data?.isBind == true) {
            val userInfoData = SettingPreference.getUserInfoData()
            userInfoData.isBind = true
            SettingPreference.saveUserInfo(userInfoData)
            if (isWithdrawLottery) {
                if (sessionId != "") {
                    isWithdrawLottery = false
                    mPresenter?.requestUserWxWithdrawLottery(sessionId)
                }
            } else {
                if (mData?.ifUse == 1 || mData2?.ifUse == 1) {
                    Toast.makeText(this@UserInfoActivity, "已提现", Toast.LENGTH_SHORT).show()
                } else {
                    if (adapter?.getSelectPosition() != -1 && mData?.id != null) {
                        mPresenter?.requestWxWithdraw(mData?.id!!)
                    }

                    if (adapter2?.getSelectPosition() != -1 && mData2?.id != null) {
                        mPresenter?.requestWxWithdraw(mData2?.id!!)
                    }
                }
            }
        } else {
//            UserDialog.showWxLogin(this)
        }
    }

    override fun wxBindFailure(errorMsg: String?) {
    }

    override fun wxWithdrawSuccess(result: WithdrawEntity) {
        Log.d(TAG, "wxWithdrawSuccess:" + result?.status + " mWithdrawNum:" + mWithdrawNum)
        request()

//        UserDialog.showWirhdrawSuccess(this, mRemainGuessNum?.toString(), data)
          MainDialog.showWithDraw(  this,
              result?.status?:0,
              result?.title?:"",
              result?.reason?:"",
              result?.buttonText?:"",
              result?.buttonStatus?:0,
              result.id,
              result. type,
              result.cash.toString(),
              false,
              Dialog(this))
        if (result?.status == 1) {
            //成功
            EventUtils.onEvent("tixian_success_show", "提现成功")
        } else {
            EventUtils.onEvent("tixian_fail_show", "提现失败")
        }
    }

    override fun wxWithdrawFailure(errorMsg: String) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show()
        EventUtils.onEvent("withdraw_fail", "提现失败")
    }

    override fun coin2cashSuccess(data: WithdrawEntity) {
        Toast.makeText(this, "兑换成功", Toast.LENGTH_SHORT).show()
//        mPresenter?.requestUserGold()
    }

    override fun coin2cashFailure(errorMsg: String) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show()
    }


    override fun userMindSuccess(data: UserInfoEntity) {
        tv_user_precautions?.text = data.title
        tv_user_precaution1?.text = data.mind
//        val minds = data.mind.split("\n")
//        var i = 0
//        while (i < precautionList.size) {
//            precautionList[i].text = minds[i]
//            i++
//        }

    }

    override fun userMindFailure() {
        layou_user_precautions.visibility = View.GONE
    }

    //兑换金币成功
    override fun coin2cashCheckSuccess(data: WithdrawEntity) {
        /*UserDialog.showExchangeCashDialog(
            this,
            data.cash,
            userData?.coinRate,
            data.sid
        )*/

//        CenterDialog.universalDialog(this,
//            "兑换现金",
//            "可兑换现金<font color=\"#FF304A\">${data.cash}</font>元 <br>" +
//                    "消耗<font color=\"#FF304A\">${DecimalFormat("0").format(data.cash!! * userData?.coinRate!!)}</font>金币",
//            "确认兑换",
//            true,
//            View.OnClickListener {
//                if (data.cash == 0.0) {
//                    Utils.showToast(this, "余额不足，快去猜歌赚钱吧")
//                } else {
//                    updateCoin2cash(data.sid)
//                }
//            })
    }

    override fun coin2cashCheckFailure(errorMsg: String) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show()
    }

    override fun userWxWithdrawLotterySuccess(data: WithdrawEntity) {
        if (data?.status == 0) {
            //成功
            Toast.makeText(this, data.reason, Toast.LENGTH_SHORT).show()
            EventUtils.onEvent("withdraw_success", "提现成功")
        } else {
            Toast.makeText(this, data?.reason, Toast.LENGTH_SHORT).show()
            EventUtils.onEvent("withdraw_fail", "提现失败")
        }
        request()
    }

    override fun userWxWithdrawLotteryFailure(errorMsg: String) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show()
    }


    //设置提现说明
    private fun setWirhdrawDescription(data: WithdrawEntity) {
        adapter2?.setSelectPosition(-1)
        adapter2?.notifyDataSetChanged()
        layout_user_withdraw_description.visibility = View.GONE

        if (data?.ifUse != 1) {
            mData = data
            mData2 = null
            if (data.status == 1) {//不显示提现说明
                if (data.type == 1) {
                    tv_user_withdraw_description_1.text = Html.fromHtml(data.desc)
                    layout_user_withdraw_description.visibility = View.VISIBLE
                    layout_user_withdraw_description_progress.visibility = View.GONE
                } else {
                    layout_user_withdraw_description.visibility = View.GONE
                }
            } else {
                if (data.ext?.title == "") {
                    layout_user_withdraw_description.visibility = View.GONE
                } else {
                    layout_user_withdraw_description.visibility = View.VISIBLE
                    tv_user_withdraw_description_1.text = Html.fromHtml(data.ext?.title)
                    tv_user_withdraw_status.text = "${data?.ext?.clock}"
                    id_progress_tv.text = "${data?.ext?.current}/${data?.ext?.max}"
                    if (data.type == 4) {
                        // id_iv_withdraw_description_icon?.setImageResource(R.drawable.icon_user_withdraw_unreceive)
                    } else if (data.type == 2) {
                        // id_iv_withdraw_description_icon?.setImageResource(R.drawable.icon_user_withdraw_receive)
                    } else if (data.type == 5) {
                        // id_iv_withdraw_description_icon?.setImageResource(R.drawable.icon_user_order)
                    }

                    if (data?.ext?.max != null) {
                        if (data?.ext?.current != null) {
                            pb_withdraw_task.progress = data.ext?.current ?: 0
                        }
                        pb_withdraw_task.max = data.ext?.max ?: 0
                    }
                    if (data.type == 1 || data.type == 3) {
                        layout_user_withdraw_description_progress.visibility = View.GONE
                    } else {
                        layout_user_withdraw_description_progress.visibility = View.VISIBLE
                    }
                    tv_user_withdraw_status.setOnClickListener {
                        when (data.type) {
                            // 1 ->  新手专享
                            2 -> JumpUtils.jumpClockInWithdrawActivity()
                            4 -> JumpUtils.jumpWelfareActivity()
                            5 -> finish()
                        }
                    }
                }
            }
        } else {
            layout_user_withdraw_description.visibility = View.GONE
        }

    }

    //设置提现说明
    private fun setWirhdrawDescription2(data: WithdrawEntity) {
        adapter?.setSelectPosition(-1)
        adapter?.notifyDataSetChanged()
        layout_user_withdraw_description.visibility = View.GONE

        if (data?.ifUse != 1) {
            mData2 = data
            mData = null
            if (data.status == 1) {//不显示提现说明
                if (data.type == 1) {
                    tv_user_withdraw_description_1.text = Html.fromHtml(data.desc)
                    layout_user_withdraw_description.visibility = View.VISIBLE
                    layout_user_withdraw_description_progress.visibility = View.GONE
                } else {
                    layout_user_withdraw_description.visibility = View.GONE
                }
            } else {
                if (data.ext?.title == "") {
                    layout_user_withdraw_description.visibility = View.GONE
                } else {
                    layout_user_withdraw_description.visibility = View.VISIBLE
                    tv_user_withdraw_description_1.text = Html.fromHtml(data.ext?.title ?: "")
                    tv_user_withdraw_status.text = "${data?.ext?.clock}"
                    id_progress_tv.text = "${data?.ext?.current}/${data?.ext?.max}"
                    //tv_user_withdraw_description_22.text = Html.fromHtml(data.ext?.desc ?: "")
                    if (data.type == 4) {
                        // id_iv_withdraw_description_icon2?.setImageResource(R.drawable.icon_user_withdraw_unreceive)
                    } else if (data.type == 2) {
                        //id_iv_withdraw_description_icon2?.setImageResource(R.drawable.icon_user_withdraw_receive)
                    }
                    //  pb_withdraw_task2.max = data.ext?.max ?: 0
                    if (data.type == 1 || data.type == 3) {
                        //      layout_user_withdraw_description_progress2.visibility = View.GONE

                    }
//                    if (data?.ext?.max != null) {
//                        if (data?.ext?.current != null) {
//                            pb_withdraw_task.progress = data.ext?.current ?: 0
//                        }
//                        pb_withdraw_task.max = data.ext?.max ?: 0
//                    }
                    if ((data.ext?.current ?: 0) >= (data.ext?.max ?: 0)) {
                            pb_withdraw_task.progress = data.ext?.max ?: 0
                        //    tv_user_withdraw_status2.text = "已完成"
                    } else {
                           pb_withdraw_task.progress = data.ext!!.current!!
                        when (data.type) {
                            2 -> {
                                //       layout_user_withdraw_description_progress2.visibility = View.VISIBLE
                                if (data.ext?.clockStatus == 0) {
                                    //         tv_user_withdraw_status2.text = "今日未打卡"
                                } else {
                                    //       tv_user_withdraw_status2.text = "今日已打卡"
                                }
                            }
                            4 -> {
                                //   layout_user_withdraw_description_progress2.visibility = View.VISIBLE
                                if (data.ext!!.current!! >= data.ext!!.max!!) {
                                    //       pb_withdraw_task2.progress = data.ext!!.max!!
                                } else {
                                    //       pb_withdraw_task2.progress = data.ext!!.current!!
                                    //      tv_user_withdraw_status2.text = "领钻石"
                                }
                            }
                            5 -> {

                            }
                        }
                    }

//                    tv_user_withdraw_status2.setOnClickListener {
//                        when (data.type) {
//                            // 1 ->  新手专享
//                            2 -> JumpUtils.jumpClockInWithdrawActivity()
//                            4 -> JumpUtils.jumpWelfareActivity()
//                        }
//                    }
                }
            }
        } else {
            layout_user_withdraw_description.visibility = View.GONE
        }
    }


    override fun onDestroy() {
        super.onDestroy()
//        withdrawListAdapter?.cancel()
    }
}