package com.mints.goodmoney.ui.activitys

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.mints.goodmoney.R
import com.mints.goodmoney.common.Constant
import com.mints.goodmoney.login.LoginApi
import com.mints.goodmoney.login.OnLoginListener
import com.mints.goodmoney.manager.UserManager
import com.mints.goodmoney.mvp.model.DrawcashBean
import com.mints.goodmoney.mvp.model.WXInfo
import com.mints.goodmoney.mvp.presenters.DrawcashPresenter
import com.mints.goodmoney.mvp.views.DrawcashView
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.goodmoney.ui.adapter.DrawcashAdapter
import com.mints.goodmoney.ui.adapter.listener.OnItemClickListener
import com.mints.goodmoney.utils.SpanUtils
import com.mints.library.utils.json.JsonUtil
import kotlinx.android.synthetic.main.activity_drawcash.*
import kotlinx.android.synthetic.main.header_layout.*
import kotlinx.android.synthetic.main.view_title.*
import net.grandcentrix.tray.AppPreferences
import java.util.*

/**
 * 描述：提现
 * 作者：孟崔广
 * 时间：2020/10/12 14:37
 */
class DrawcashActivity : BaseActivity(),
        DrawcashView, View.OnClickListener, OnItemClickListener, OnLoginListener {

    private val drawcashPresenter by lazy { DrawcashPresenter() }
    private val userManager by lazy { UserManager.getInstance() }
    private val loginApi by lazy { LoginApi() }
    private lateinit var drawcashAdapter: DrawcashAdapter
    private var priceList: MutableList<DrawcashBean.CashOutMoneyArrBean>? = null
    private var wxInfo: WXInfo? = null
    private var userConfig: DrawcashBean? = null

    private var isLoadRvItem: Boolean = true //是否首次加载rv item

    override fun getContentViewLayoutID() = R.layout.activity_drawcash

    override fun isApplyKitKatTranslucency() = false

    override fun initViewsAndEvents() {
        tv_title.text = "提现"
        iv_left_icon.visibility = View.VISIBLE
        iv_left_icon.setImageResource(R.mipmap.ic_arrow_back)
        tv_right_subtitle.visibility = View.VISIBLE
        tv_right_subtitle.text = "提现记录"

        view_title.text = "提现规则"

        drawcashPresenter.attachView(this)
//        initText()
        initListener()
    }

    override fun onResume() {
        super.onResume()

        drawcashPresenter.getUserTaskMsg()
    }

    override fun onDestroy() {
        super.onDestroy()

        loginApi.setOnLoginListener(null)

        drawcashPresenter.detachView()
    }

    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.iv_left_icon -> finish()
            R.id.tv_right_subtitle -> {
                // 是否登录
                if (!userManager.userIsLogin()) {
                    readyGo(LoginActivity::class.java)
                    return
                }

                readyGo(DrawcashRecordActivity::class.java)
            }
            R.id.rl_coin -> {
//                readyGo(CoinRecordActivity::class.java)
            }
            R.id.tvDrawcashWx -> {
                if (!TextUtils.isEmpty(userConfig?.openid)) {
                    return
                }

                val wechat = ShareSDK.getPlatform(Wechat.NAME)
                if (!wechat.isClientValid) {
                    showToast("请先安装微信")
                    return
                }

                loginApi.setOnLoginListener(this)
                loginApi.setPlatform(Wechat.NAME)
                loginApi.login(this)
            }
            R.id.tvDrawcashNext -> {
                if (priceList != null && priceList!!.size > 0) {
                    // 校验当前金币< 选择金币 =提示 去做任务
                    if (userConfig?.coin!! < priceList!![drawcashAdapter.getPosition()].money * 10000) {
                        showToast("金币不足，快去做任务吧")
                        return
                    }

                    // 是否登录
                    if (!userManager.userIsLogin()) {
                        readyGo(LoginActivity::class.java)
                        return
                    }

                    // 是否绑定手机号
                    if (TextUtils.isEmpty(userManager.mobile)) {
                        val bundle = Bundle()
                        bundle.putBoolean(Constant.LOGIN_FLAG, true)
                        readyGo(LoginActivity::class.java, bundle)
                        return
                    }

                    // 授权判断
                    if (TextUtils.isEmpty(userConfig?.openid)) {
                        showToast("微信未授权")
                        return
                    }

                    drawcashPresenter.saveTerminalInfo(priceList!![drawcashAdapter?.getPosition()].money)
                }
            }
        }
    }

    override fun getUserTaskMsgSuc(data: DrawcashBean) {
        userConfig = data

        tvDrawcashExplain.text = data.drawcashRule
        tvDrawcashHint.text = data.drawcashHint
        tvDrawcashGold.text = "${data.getCoin()}"
        if (TextUtils.isEmpty(data.openid)) {
            tvDrawcashWx.setText("去授权")
            tvDrawcashName.setText("微信昵称")
        } else {
            tvDrawcashWx.setText("已授权")
            tvDrawcashName.setText(data.nickName)
        }

        if (isLoadRvItem) {
            priceList = data.cashOutMoneyArr
            initRvView()
        }
    }

    override fun editUserMsgSuc() {
        showToast("微信授权成功")

        drawcashPresenter.getUserTaskMsg()
    }

    override fun onLogin(platform: String?, res: HashMap<String, Any>): Boolean {
        try {
            wxInfo = WXInfo()
            wxInfo?.let {
                it.setUnionid(res["unionid"].toString() + "")
                it.setOpenid(res["openid"].toString() + "")
                it.setProvince(res["province"].toString() + "")
                it.setCity(res["city"].toString() + "")
                it.setCountry(res["country"].toString() + "")
                it.setHeadimgurl(res["headimgurl"].toString() + "")
                it.setNickname(res["nickname"].toString() + "")
                it.setSex((res["sex"].toString() + "").toInt())
            }

            if (!isFinishing) {
                drawcashPresenter.editUserMsg(JsonUtil.toJson(wxInfo))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    private fun initText() {
        tvDrawcashExplain.setText(
                SpanUtils()
                        .append("提现说明：")
                        .append("\n")
                        .append("1、所有提现金额【无门槛】直接提现！新用户提现秒到账！")
                        .append("\n")
                        .append("2、由于提现需要实名制，非实名用户账号无法支持提现，请务必使用实名认证过的账号提现！")
                        .append("\n")
                        .append("3、单笔提现金额最低" + 0.3 + "元，最高" + 1000 + "元。")
                        .append("\n")
                        .append("4、提现申请将在3-5个工作日审核到账，请耐心等待。")
                        .append("\n")
                        .append("5、每日可申请提现一次，若当日限额已满，请次日申请。")
                        .create())

        tvDrawcashHint.text = "* 如您或好友通过刷机等违规操作获取非法收益，平台将视情况扣除违规所得或冻结账号。" +
                "\n* 最终解释权归本公司所有。"

    }

    private fun initRvView() {
        val gridLayoutManager = GridLayoutManager(this, 3)
        rvCash.layoutManager = gridLayoutManager
        drawcashAdapter = priceList?.let { DrawcashAdapter(it) }!!
        rvCash.adapter = drawcashAdapter
        drawcashAdapter.setOnItemClickListener(this)

        isLoadRvItem = false
    }

    private fun initListener() {
        iv_left_icon.setOnClickListener(this)
        tv_right_subtitle.setOnClickListener(this)
        rl_coin.setOnClickListener(this)
        tvDrawcashWx.setOnClickListener(this)
        tvDrawcashNext.setOnClickListener(this)
    }

    override fun onItemClick(view: View?, position: Int) {
        drawcashAdapter.setPosition(position)
        drawcashAdapter.notifyDataSetChanged()
    }
}