package com.yidianling.user.mine

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.*
import android.text.style.AbsoluteSizeSpan
import android.view.View
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.TransferCacheUtils
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.MoneyValueFilter
import com.ydl.ydlcommon.view.NoBindPhoneDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.R
import com.yidianling.user.UserConstants
import com.yidianling.user.UserHelper
import com.yidianling.user.api.service.IUserService
import com.yidianling.user.api.utils.UserApiServiceUtils
import com.yidianling.user.http.UserHttpImpl
import com.yidianling.user.http.request.CodeParam
import com.yidianling.user.mine.bean.AccountBean
import com.yidianling.user.mine.bean.DefaultAccountCmd
import com.yidianling.user.mine.bean.WithDrawCmd
import com.yidianling.user.mine.data.AppDataManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_mine_activity_with_draw.*
import java.util.concurrent.TimeUnit


/**
 * 提现申请
 */
class WithDrawActivity : BaseActivity() {
    private var accountBean: AccountBean? = null
    private var hasDefault = false//是否有默认账户
    private var isCodeCompelte = false//验证码是否完整
    private var isMoneyComplete = false//是否有输入金额
    private var list: MutableList<AccountBean>? = null
    private var maxMoney: String? = null
    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(true, true)
    }
    companion object {
        private const val CHOOSE_ACCOUNT_REQUEST_CODE = 1102
        private const val ADD_ACCOUNT_REQUEST_CODE = 1103
        const val INTENT_ACCOUNT_DATA = "intent_account_data"
        const val INTENT_ACCOUNT_MONEY = "intent_account_money"
        var time: Long = 60//本地维护一个静态变量：验证码倒计时时间
        var isFirstIn = true//本地维护一个静态变量：是否第一次进入--第一次进入，发送验证码显示初始状态；再次进入，根据time变量判断显示状态

        fun start(activity: Activity, money: String) {
            val intent = Intent(activity, WithDrawActivity::class.java)
            intent.putExtra(INTENT_ACCOUNT_MONEY, money)
            activity.startActivity(intent)
        }
    }

    override fun layoutResId(): Int {
        return R.layout.user_mine_activity_with_draw
    }

    override fun initDataAndEvent() {
        maxMoney = intent.getStringExtra(INTENT_ACCOUNT_MONEY)
        val money = StringBuffer()
        money.append("余额").append(maxMoney).append("元")
        tv_max_money.text = money.toString()
        ll_choose.setOnClickListener {
            if (list == null || list!!.isEmpty()) {//没有帐号时，去添加账户页面
                AddAccountActivity.startForResult(this, ADD_ACCOUNT_REQUEST_CODE)
            } else {//有帐号时，去选择账户页面
                ChooseAccountActivity.startForResult(this, list!!, CHOOSE_ACCOUNT_REQUEST_CODE)
            }
        }

        tv_all.setOnClickListener {
            //            if (maxMoney?.contains(".")!!) {
//                var index = maxMoney!!.indexOf(".")
//                et_money.setText(maxMoney!!.substring(0, index))
//            } else {
            et_money.setText(maxMoney)
//            }
        }

        tv_get_code.setOnClickListener {
            getCode()
        }

        btn_ensure.setOnClickListener {
            withDraw()
        }

        var spannableString = SpannableString("请输入验证码")
        val ass = AbsoluteSizeSpan(17, true)//设置字体大小 true表示单位是sp
        spannableString.setSpan(ass, 0, spannableString.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        et_code.hint = SpannedString(spannableString)

        et_money.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(s)) {
                    if (!s.toString().startsWith(".")) {
                        //输入金额大于余额时，出现提示
                        if (maxMoney!!.toFloat() < s.toString().toFloat()) {
                            tv_warn.visibility = View.VISIBLE
                        } else {
                            tv_warn.visibility = View.GONE
                        }
                    }
                    isMoneyComplete = true
                    checkEnsureEnable()
                } else {
                    isMoneyComplete = false
                    checkEnsureEnable()
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        et_money.filters = arrayOf<InputFilter>(MoneyValueFilter())

        et_code.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(s) && s!!.length == 4) {
                    isCodeCompelte = true
                    checkEnsureEnable()
                } else {
                    isCodeCompelte = false
                    checkEnsureEnable()
                }
            }
        })
        getData()
        btn_ensure.setDisableColor(resources.getColor(R.color.user_c8c8c8))
        checkEnsureEnable()

        //根据isFirstIn和time两个变量判断当前状态
        //如果不是第一次进入
        if (!isFirstIn) {
            //time小于初始时间，说明之前已经发送过验证码，且验证码发送还在60s倒计时内，此时直接显示倒计时
            if (time < 60) {
                initTimer(time)
            } else {//等于初始时间：说明未发送过验证码，或者验证码已经60s倒计时完成
                tv_get_code.text = "发送验证码"
            }
        }
    }

    /**
     * 提现
     */
    private fun withDraw() {
        if (accountBean == null) {
            return
        }
        var money = et_money.text.trim().toString()
        if (money.startsWith("00")) {
            ToastUtil.toastShort("输入金额格式错误")
            return
        }
        if (money.startsWith(".")) {
            ToastUtil.toastShort("输入金额格式错误")
            return
        }
        if (maxMoney!!.toFloat() < money.toFloat()) {
            ToastUtil.toastShort("可提现余额不足")
            return
        }

        var param = WithDrawCmd(accountBean!!.id, money, et_code.text.toString())
        showProgressDialog()
        AppDataManager.getHttp().applyAccount(param)
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    dismissProgressDialog()
                    WithDrawSuccessActivity.start(this, accountBean!!.remark!!)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        dismissProgressDialog()
                        ToastUtil.toastShort(msg)
                    }
                })
    }

    /**
     * 获取验证码
     */
    @SuppressLint("CheckResult")
    private fun getCode() {
        //未绑定手机号弹窗提示去绑定
        if (!UserHelper.isBindPhone()) {
            var dialog = NoBindPhoneDialog(this) {
                startActivity(UserApiServiceUtils.provideUserApiService().inputPhoneIntent(mContext, UserConstants.BIND_PHONE_ACTION))
            }
            dialog.show()
            return
        }

        if (time < 60) {
            if (timerSub != null) {//判断当前是否发送过验证码
                timerSub!!.dispose()
            }
            initTimer(time)
        } else {
            var phone = ""
            try {
                phone = ModularServiceManager.provide(IUserService::class.java).getUserInfo()?.phone?:""
            } catch (e: Exception) { }
            var params = CodeParam("0086", phone, "withdraw")
            val userHttp = UserHttpImpl.getInstance()
            userHttp.code(params)
                    .compose(RxUtils.resultData())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe { disposable -> showProgressDialog("") }
                    .doAfterTerminate({ this.dismissProgressDialog() })
                    .subscribe(Consumer {
                        ToastUtil.toastShort("验证码已发送")
                        isFirstIn = false
                        initTimer(60)
                    }, object : ThrowableConsumer() {
                        override fun accept(msg: String) {
                            ToastHelper.show(msg)
                            LogHelper.getInstance().writeLogSync(String.format("获取验证码失败：%s", msg))
                        }
                    })
        }
    }


    private var timerSub: Disposable? = null

    private fun initTimer(allTime: Long) {
        timerSub = Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .take(allTime)
                .map {
                    time = allTime - 1 - it
                    String.format("重新发送(%d)", time)
                }
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe {
                    tv_get_code.isEnabled = false
                    tv_get_code.setTextColor(-0x525253)
                }
                .subscribe({
                    tv_get_code.text = it
                }, {}, {
                    time = 60
                    tv_get_code.text = "重新发送"
                    tv_get_code.isEnabled = true
                    tv_get_code.setTextColor(-0xb62d7f)
                })
    }

    @SuppressLint("CheckResult")
    private fun getData() {
        showProgressDialog()
        AppDataManager.getHttp().getAccountList()
                .compose(RxUtils.resultData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    dismissProgressDialog()
                    if (it == null || it.isEmpty()) {
                        showNoAccountView(false)
                    } else {
                        showData(it)
                    }
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        dismissProgressDialog()
                        ToastHelper.show(msg)
                    }
                })
    }

    /**
     * 无提现帐号:
     * hasAccount:true 有账户，无默认账户
     *            false 无账户
     */
    private fun showNoAccountView(hasAccount: Boolean) {
        this.hasDefault = false

        if (hasAccount) {
            tv_account_name.text = "请选择提现帐号"
            account_icon.setImageResource(R.drawable.user_mine_ico_warn)
        } else {
            tv_account_name.text = "您还未添加提现帐号，点击添加"
            account_icon.setImageResource(R.drawable.user_mine_ico_warn)
        }
        tv_account_num.text = ""
        tv_remark.text = ""

        checkEnsureEnable()
    }

    /**
     * 从列表中筛选出默认帐号并更新ui
     */
    private fun showData(list: MutableList<AccountBean>) {
        var hasDefaultAccount = false
        list.forEach {
            if (it.isDefault == 1) {
                showData(it)
                hasDefaultAccount = true
                return@forEach
            }
        }
        if (!hasDefaultAccount) {
            showNoAccountView(true)
        }
        this.list = list
    }

    /**
     * 判断确认提现按钮是否可以点击、获取验证码按钮是否可以点击
     * @param hasDefault 是否有默认账户
     * @param isCodeCompelte 验证码是否完整
     * @param isMoneyComplete 是否有输入金额
     */
    private fun checkEnsureEnable() {
        tv_get_code.isEnabled = hasDefault
        if (hasDefault && isCodeCompelte && isMoneyComplete) {
            btn_ensure.enableButton()
        } else {
            btn_ensure.disableButton()
        }
    }

    /**
     * 将该账户设置默认账户
     */
    @SuppressLint("CheckResult")
    private fun setDefault(bean: AccountBean) {
        showProgressDialog()

        var parms = DefaultAccountCmd(bean.id)
        AppDataManager.getHttp().setDefaultAccount(parms)
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    dismissProgressDialog()
                    //设置成功后更新本地数据list中默认帐号（确保用户再次点击到选择帐号页面时，默认帐号数据是正确的）
                    if (list != null) {
                        list!!.forEach {
                            if (TextUtils.equals(it.id, bean.id)) {
                                it.isDefault = 1
                            }
                        }
                    }
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        dismissProgressDialog()
                    }
                })
    }

    /**
     * 将默认帐号信息更新在ui上
     */
    private fun showData(bean: AccountBean) {
        accountBean = bean
        when (bean.type) {
            1 -> tv_account_name.text = "支付宝"
            2 -> tv_account_name.text = "微信"
            3 -> tv_account_name.text = bean.bankName
        }
        if (bean.type == 1) {
            account_icon.setImageResource(R.drawable.user_mine_alipay_round)
        } else {
            GlideApp.with(this)
                    .load(bean.bankIcon)
                    .into(account_icon)
        }
        tv_account_num.text = bean.account + " " + bean.cashName
        tv_remark.text = bean.remark

        hasDefault = true
        checkEnsureEnable()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == CHOOSE_ACCOUNT_REQUEST_CODE) {//选择帐号返回
            val list = TransferCacheUtils.getTransferData(INTENT_ACCOUNT_DATA) as MutableList<AccountBean>
            if (list == null || list.isEmpty()) {
                showNoAccountView(false)
            } else {
                showData(list)
                list.forEach {
                    if (it.isDefault == 1) {
                        setDefault(it)
                        return@forEach
                    }
                }
            }
            TransferCacheUtils.removeTransferData(INTENT_ACCOUNT_DATA)
            //将选择的帐号设置为默认帐号
        }
        if (requestCode == ADD_ACCOUNT_REQUEST_CODE) {//添加帐号返回
            getData()
        }
    }
}