package com.bc_chat.mine.userinfo

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.View
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.entity.User
import com.bc_chat.bc_base.http.Api
import com.bc_chat.bc_base.utils.AppConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.view.AddressDialogFragment
import com.bc_chat.bc_base.view.PictureDialogFragment
import com.bc_chat.bc_base.view.QrCodeDialogFragment
import com.bc_chat.mine.R
import com.bc_chat.mine.contract.UpdateContract
import com.bc_chat.mine.databinding.ActivityUserInfoBinding
import com.bc_chat.mine.presenter.UpdatePresenter
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.dto.ProvinceDTO
import com.zhaohaoting.framework.utils.RxSchedulers
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.Utils
import com.zhaohaoting.framework.utils.glid.GlideUtils
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import com.zhaohaoting.framework.view.picker.framework.entity.Province
import io.reactivex.Observable
import io.rong.contactcard.message.ContactMessage
import io.rong.imkit.RongIM
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import org.jetbrains.anko.bundleOf
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/2/22
 * email：526309416@qq.com
 * desc：个人资料
 */
@Route(path = RouteConfig.USER_INFO_ACTIVITY)
class UserInfoActivity : BaseActivity<UpdatePresenter>(), View.OnClickListener, UpdateContract.View, Observer<String> {

    companion object {
        const val REQUESTCODE_NICK_NAME = 311
        const val REQUESTCODE_SIGNATURE = 312
    }

    var user: User? = null

    private val binding by lazy {
        rootDataBinding as ActivityUserInfoBinding
    }

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

    override fun getLayoutResId(): Int = R.layout.activity_user_info

    override fun initialize() {
        binding.onClickEvent = this
        user = AppConfig.instance.getUser()
        initAreaData()
        GlideUtils.loadCircleImage(this, user?.photo, binding.ivPhoto)
        binding.tvNickName.text = user?.remark ?: user?.nickname
        binding.tvSignature.text = user?.introduction
        binding.tvCity.text = if (TextUtils.isEmpty(user?.province)) "" else user?.province + " " + if (TextUtils.isEmpty(user?.city)) "" else user?.city
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
        if (Const.SERVICE_ID.contains(user?.userId!!)){
            binding.llQrCode.visibility = View.GONE
        }
    }

    override fun onEvent(key: String?, var1: String?) {
        if (key.equals(Const.ObserverKey.FORWARD_MESSAGE)){
            finish()
        }
    }

    private fun initAreaData() {
        val disposable = Observable.fromCallable<ArrayList<Province>> {
            val json = Utils.getJson(this, "province.json")
            ProvinceDTO.parseAreaJson(json)
        }.compose(RxSchedulers.applyObservableAsync())
                .subscribe { }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ll_photo -> judgePermission(Const.Permission.Key.STORAGE_CAMERA, *Const.Permission.Value.STORAGE_CAMERA)
            R.id.ll_nick_name -> {
                ARouter.getInstance().build(RouteConfig.EDIT_USER_ACTIVITY)
                        .withString("action", Const.Action.UPDATE_USER_INFO)
                        .withString("content", user?.nickname)
                        .withString("key", "nick_name")
                        .navigation(this, REQUESTCODE_NICK_NAME)
            }
            R.id.ll_qr_code -> {
                val qrCodeDialogFragment = QrCodeDialogFragment()
                val user = AppConfig.instance.getUser()
                qrCodeDialogFragment.arguments = bundleOf("photo" to user.photo, "qrCodeName" to "user_${user.userId}_qr_code", "url" to "${Api.SHARE_PATH}?source=bc_chat&type=${Const.QrType.USER_TYPE}&id=${user.userId}")
                qrCodeDialogFragment.show(supportFragmentManager)
            }
            R.id.ll_signature -> {
                ARouter.getInstance().build(RouteConfig.EDIT_USER_ACTIVITY)
                        .withString("action", Const.Action.UPDATE_USER_INFO)
                        .withString("content", user?.introduction)
                        .withString("key", "signature")
                        .navigation(this, REQUESTCODE_SIGNATURE)
            }
            R.id.ll_business_card -> {
                val sendUserInfo = RongUserInfoManager.getInstance().getUserInfo(RongIMClient.getInstance().currentUserId)
                val sendUserName = if (sendUserInfo == null) "" else sendUserInfo.name
                val friendPortrait = if (sendUserInfo.portraitUri == null) "" else sendUserInfo.portraitUri.toString()
                val contactMessage = ContactMessage.obtain(sendUserInfo.userId,
                        sendUserInfo.name, friendPortrait, RongIMClient.getInstance().currentUserId, sendUserName, "")
                ARouter.getInstance().build(RouteConfig.FORWARD_ACTIVITY).withParcelableArrayList("selectList", arrayListOf(Message.obtain(sendUserInfo.userId, Conversation.ConversationType.PRIVATE, contactMessage))).navigation()
            }
            R.id.ll_city -> {
                val addressDialogFragment = AddressDialogFragment()
                addressDialogFragment.show(supportFragmentManager, "AddressDialogFragment")
                addressDialogFragment.setOnAddressPickListener { province, city, county ->
                    binding.tvCity.text = "${city.areaName} ${county.areaName}"
                    presenter.updateUserInfo(province = city.areaName, city = county.areaName, type = 4)
                }
            }
        }
    }

    override fun requestPermissionSuccess(requestCode: Int) {
        if (requestCode == Const.Permission.Key.STORAGE_CAMERA) {
            val pictureDialogFragment = PictureDialogFragment()
            pictureDialogFragment.arguments = bundleOf("isCrop" to true, "aspectX" to 1000, "aspectY" to 1000, "width" to 300, "height" to 300)
            pictureDialogFragment.setPicturePhotoPathLinstener {
                GlideUtils.loadCircleImage(this, "file://$it", binding.ivPhoto)
                presenter.upload(arrayListOf(it))
            }
            pictureDialogFragment.show(supportFragmentManager, "pictureDialogFragment")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            REQUESTCODE_NICK_NAME -> binding.tvNickName.text = data?.getStringExtra("content")
            REQUESTCODE_SIGNATURE -> binding.tvSignature.text = data?.getStringExtra("content")
        }
    }

    override fun updateSuccess(nickname: String?, photo: String?, introduction: String?, province: String?, city: String?, type: Int) {
        val user = AppConfig.instance.getUser()
        when (type) {
            2 -> {
                val currentUserId = RongIM.getInstance().currentUserId
                val userInfo = RongUserInfoManager.getInstance().getUserInfo(currentUserId)
                userInfo.portraitUri = Uri.parse(photo)
                RongIM.getInstance().refreshUserInfoCache(userInfo)
                RongIM.getInstance().setCurrentUserInfo(userInfo)
                user.photo = photo
            }
            4 -> {
                user.province = province
                user.city = city
            }
        }
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.UPDATE_MINE_USER_INFO, user.userId)
    }

    override fun updateFailure() {
    }

    override fun uploadSuccess(paths: MutableList<String>?) {
        presenter.updateUserInfo(photo = paths!![0], type = 2)
    }

    override fun uploadFailure(e: Exception?) {
        ToastUtils.show("图片上传失败")
    }

    override fun onDestroy() {
        super.onDestroy()
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
    }
}
