package com.yidianling.user.mine

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
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.utils.TransferCacheUtils
import com.ydl.ydlcommon.view.ListNoCancelDialog
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.R
import com.yidianling.user.mine.WithDrawActivity.Companion.INTENT_ACCOUNT_DATA
import com.yidianling.user.mine.adapter.AccountListAdapter
import com.yidianling.user.mine.bean.AccountBean
import com.yidianling.user.mine.bean.DefaultAccountCmd
import com.yidianling.user.mine.data.AppDataManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.user_mine_activity_choose_account.*

/**
 * 选择提现账户页面
 */
class ChooseAccountActivity : BaseActivity() {
    private var adapter: AccountListAdapter? = null
    private var dataLists: MutableList<AccountBean>? = null

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(true, true)
    }

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

    override fun initDataAndEvent() {
        title_bar.setOnLeftTextClick { _, _ -> onBackPressed() }
        dataLists = TransferCacheUtils.getTransferData(INTENT_LIST) as MutableList<AccountBean>
        TransferCacheUtils.removeTransferData(INTENT_LIST)
        adapter = AccountListAdapter(this, AccountListAdapter.OnChooseItemListener {

            val intent = Intent()
            TransferCacheUtils.putTransferData(INTENT_ACCOUNT_DATA, it)
            setResult(Activity.RESULT_OK, intent)
            finish()
        })
        btn_add.setOnClickListener {
            AddAccountActivity.startForResult(this, ADD_ACCOUNT_REQUEST_CODE)
        }
        adapter!!.setList(dataLists)
        lv_content.adapter = adapter
        lv_content.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            adapter!!.checkChoose(position)
        }
        lv_content.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
            val list = mutableListOf<String>()
            list.add("编辑")
            list.add("删除")
            val builder = ListNoCancelDialog.Builder(this, list, 0)
            builder.SetOnItemClickLister(object : ListNoCancelDialog.Builder.OnItemClickLister {
                override fun onItemClick(dialog: Dialog?, view: View?, index: Int) {
                    val name = list[index]
                    when (name) {
                        "编辑" -> {
                            EditAccountActivity.startForResult(this@ChooseAccountActivity, dataLists!![position], INTENT_DATA_REQUEST_CODE)
                            dialog!!.dismiss()
                        }
                        "删除" -> {
                            deleteAccount(dataLists!![position])
                            dialog!!.dismiss()
                        }
                    }
                }

                override fun onItemLongClick(dialog: Dialog?, view: View?, position: Int) {
                }

            })
            if (!ChooseAccountActivity@this.isFinishing){
                builder.create().show()
            }
            true
        }
    }

    /**
     * 删除帐号
     */
    @SuppressLint("CheckResult")
    private fun deleteAccount(bean: AccountBean) {
        showProgressDialog()
        val parms = DefaultAccountCmd(bean.id)
        AppDataManager.getHttp().deleteAccount(parms)
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    dismissProgressDialog()
                    ToastUtil.toastShort("帐号删除成功")
                    adapter!!.deleteAccount(bean)
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        dismissProgressDialog()
                        ToastUtil.toastShort(msg)
                    }
                })
    }


    override fun onBackPressed() {
        val intent = Intent()
        TransferCacheUtils.putTransferData(INTENT_ACCOUNT_DATA, adapter!!.data)
        setResult(Activity.RESULT_OK, intent)
        super.onBackPressed()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }

        if (requestCode == INTENT_DATA_REQUEST_CODE) {//编辑帐号页面返回
            val accountBean: AccountBean = TransferCacheUtils.getTransferData(INTENT_DATA) as AccountBean
            dataLists!!.forEach {
                if (TextUtils.equals(it.id, accountBean.id)) {
                    it.account = accountBean.account
                    it.cashName = accountBean.cashName
                }
            }
            adapter!!.notifyDataSetChanged()
            TransferCacheUtils.removeTransferData(INTENT_DATA)
        }

        try {//添加帐号页面返回
            val bean = data?.getParcelableExtra<AccountBean>(ADD_ACCOUNT_REQUEST_KEY)
            bean?.let {
                dataLists?.add(1, bean)
                adapter?.notifyDataSetChanged()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    companion object {
        const val INTENT_LIST = "intent_list"
        const val INTENT_DATA = "intent_data"
        const val INTENT_DATA_REQUEST_CODE = 1024
        //添加帐号
        const val ADD_ACCOUNT_REQUEST_CODE = 1025
        const val ADD_ACCOUNT_REQUEST_KEY = "add_key"
        fun startForResult(activity: Activity, list: MutableList<AccountBean>, code: Int) {
            val intent = Intent(activity, ChooseAccountActivity::class.java)
            TransferCacheUtils.putTransferData(INTENT_LIST, list)
            activity.startActivityForResult(intent, code)
        }
    }
}
