package com.bc_chat.mine.userinfo

import android.app.Activity
import android.content.Intent
import android.text.InputFilter
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.utils.AppConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.mine.R
import com.bc_chat.mine.contract.UpdateContract
import com.bc_chat.mine.databinding.ActivityEditUserBinding
import com.bc_chat.mine.presenter.UpdatePresenter
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.utils.DensityUtil
import com.zhaohaoting.framework.utils.RealNameInputFilter
import com.zhaohaoting.framework.utils.SimpleTextWatcher
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.RongIM
import io.rong.imkit.userInfoCache.RongUserInfoManager
import java.lang.Exception

/**
 * author：Created by zhaohaoting on 2019/2/21
 * email：526309416@qq.com
 * desc：个性签名和昵称修改
 */
@Route(path = RouteConfig.EDIT_USER_ACTIVITY)
class EditUserInfoActivity : BaseActivity<UpdatePresenter>(), UpdateContract.View {

    @Autowired
    @JvmField
    var key: String? = null

    @Autowired
    @JvmField
    var action: String? = null

    @Autowired
    @JvmField
    var content: String? = ""


    var lengthFilter: InputFilter.LengthFilter? = null

    private val binding by lazy {
        rootDataBinding as ActivityEditUserBinding
    }

    override fun initPresenter(): UpdatePresenter = UpdatePresenter(this)

    override fun initialize() {
        ARouter.getInstance().inject(this)
        val nameInputFilter = RealNameInputFilter()
        when (key) {
            NICK_NAME -> {
                title = "修改昵称"
                lengthFilter = InputFilter.LengthFilter(15)
                binding.etContent.filters = arrayOf(lengthFilter, nameInputFilter)
                binding.etContent.maxLines = 1
                binding.ivDelete.gone()
                binding.tvTextCount.gone()
                binding.ivDelete.setOnClickListener {
                    binding.etContent.setText("")
                }
                binding.etContent.hint = "昵称"
                binding.etContent.addTextChangedListener(object : SimpleTextWatcher() {
                    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                        if (TextUtils.isEmpty(s)) {
                            binding.ivDelete.gone()
                        } else {
                            binding.ivDelete.visible()
                        }
                        invalidateOptionsMenu()
                    }
                })
            }
            SIGNATURE -> {
                title = "个性签名"
                lengthFilter = InputFilter.LengthFilter(60)
                binding.etContent.filters = arrayOf(lengthFilter)
                binding.etContent.height = DensityUtil.dip2px(this, 200f)
                binding.ivDelete.gone()
                binding.tvTextCount.visible()
                binding.tvTextCount.text = 60.toString()
                binding.etContent.hint = "签名"
                binding.etContent.addTextChangedListener(object : SimpleTextWatcher() {
                    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                        binding.tvTextCount.text = (60 - s.length).toString()
                        invalidateOptionsMenu()
                    }
                })
            }
        }
        binding.etContent.setText(content)
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        super.onPrepareOptionsMenu(menu)
        menu?.clear()
        val content = binding.etContent.text.toString()
        if (this.content == null) this.content = ""
        if (!TextUtils.isEmpty(content) && !this.content.equals(content)) {
            menu?.add(100, 101, 0, "保存")?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        }
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        val content = binding.etContent.text.trim().toString()
        if (Const.Action.UPDATE_USER_INFO.equals(action)) {
            if (NICK_NAME.equals(key)) {
                presenter.updateUserInfo(nickname = content, type = 1)
            } else {
                presenter.updateUserInfo(introduction = content, type = 3)
            }
        } else {
            setResult(Activity.RESULT_OK, Intent().putExtra(CONTENT, content))
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_edit_user
    }

    override fun updateSuccess(nickname: String?, photo: String?, introduction: String?, province: String?, city: String?, type: Int) {
        val user = AppConfig.instance.getUser()
        val intent = Intent()
        when (type) {
            1 -> {
                val currentUserId = RongIM.getInstance().currentUserId
                val userInfo = RongUserInfoManager.getInstance().getUserInfo(currentUserId)
                if (userInfo != null) {
                    userInfo.name = nickname
                    RongIM.getInstance().refreshUserInfoCache(userInfo)
                    RongIM.getInstance().setCurrentUserInfo(userInfo)
                }
                user.nickname = nickname
                intent.putExtra(CONTENT, nickname)
            }
            3 -> {
                user.introduction = introduction
                intent.putExtra(CONTENT, introduction)
            }
        }
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.UPDATE_MINE_USER_INFO, user.userId)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun updateFailure() {
    }

    override fun uploadSuccess(paths: MutableList<String>?) {
    }

    override fun uploadFailure(e: Exception?) {
    }

    companion object {
        const val KEY = "key"
        const val CONTENT = "content"
        const val NICK_NAME = "nick_name"
        const val SIGNATURE = "signature"
    }

}