WithDrawActivity.kt 15.7 KB
Newer Older
ydl committed
1 2 3 4 5 6 7 8 9 10
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
11
import com.ydl.ydlcommon.bean.StatusBarOptions
ydl committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
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
51 52 53
    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(true, true)
    }
ydl committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    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()
        }
    }
}