package com.bc_chat.account

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.account.contract.RegisterContract
import com.bc_chat.account.databinding.ActivityPerfectInfoBinding
import com.bc_chat.account.presenter.RegisterPresenter
import com.bc_chat.bc_base.WebViewActivity
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.StringUtils
import com.bc_chat.bc_base.view.AddressDialogFragment
import com.bc_chat.bc_base.view.PictureDialogFragment
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.dto.ProvinceDTO
import com.zhaohaoting.framework.utils.Logger
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.view.picker.framework.entity.Province
import io.reactivex.Observable
import org.jetbrains.anko.bundleOf
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/2/21
 * email：526309416@qq.com
 * desc：完善资料
 */
@Route(path = RouteConfig.PERFECT_INF_ACTIVITY)
class PerfectInfoActivity : BaseActivity<RegisterPresenter>(), View.OnClickListener, NavigationCallback, RegisterContract.View {

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

    private val photoUrl: MutableList<String> = arrayListOf()
    private var mProvince: String? = null
    private var mCity: String? = null
    private var mCounty: String? = null

    private val binding by lazy {
        rootDataBinding as ActivityPerfectInfoBinding
    }
    private val phone by lazy {
        intent.getStringExtra("phone")
    }
    private val password by lazy {
        intent.getStringExtra("password")
    }

    override fun initPresenter(): RegisterPresenter? {
        return RegisterPresenter(this)
    }

    private val handler = Handler(Looper.getMainLooper())

    override fun initialize() {
        binding.onClickEvent = this
        val protocol = binding.tvProtocol.text
        StringUtils.protocol(this, protocol, binding.tvProtocol) {
            presenter.loadWebPage(Const.WebPageType.USER_PROTOCOL)
        }
        initAreaData()
    }

    override fun showLoading(vararg task: Any?) {
        super.showLoading(task)
        binding.btnCommit.isEnabled = false
    }

    override fun registerFailure(exception: Exception?) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            binding.btnCommit.isEnabled = true
        } else {
            handler.post {
                binding.btnCommit.isEnabled = true
                dismissLoading(null)
            }
        }
    }

    override fun registerSuccess(userId: String?) {
        handler.post {
            binding.btnCommit.isEnabled = true
            dismissLoading(null)
            arrivalMain()
        }
    }

    override fun loadWebPageSuccess(content: String) {
        WebViewActivity.startActivity(this, content, "用户协议", 1)
    }

    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 onCreateOptionsMenu(menu: Menu): Boolean {
//        menu.add("跳过").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        presenter.register(phone, password, if (photoUrl.size > 0) photoUrl[0] else null,
                binding.tvNickName.text.toString().trim(), binding.tvSignature.text.toString().trim(), mProvince, mCity)
        return true
    }


    override fun uploadSuccess(paths: MutableList<String>?) {
        photoUrl.addAll(paths!!)
        binding.btnCommit.isEnabled = true
    }

    override fun uploadFailure(e: Exception?) {
        binding.btnCommit.isEnabled = true
    }

    private fun arrivalMain() {
        ARouter.getInstance().build(RouteConfig.MAIN_ACTIVITY).navigation(this, this)
    }

    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.PERFECT_INFO)
                        .withString("key", "nick_name")
                        .withString("content", binding.tvNickName.text.toString())
                        .navigation(this, REQUESTCODE_NICK_NAME)
            }
            R.id.ll_qr_code -> ToastUtils.show("二维码")
            R.id.ll_signature -> {
                ARouter.getInstance().build(RouteConfig.EDIT_USER_ACTIVITY)
                        .withString("action", Const.Action.PERFECT_INFO)
                        .withString("key", "signature")
                        .withString("content", binding.tvSignature.text.toString())
                        .navigation(this, REQUESTCODE_SIGNATURE)
            }
            R.id.ll_business_card -> ToastUtils.show("名片")
            R.id.ll_city -> {
                val addressDialogFragment = AddressDialogFragment()
                addressDialogFragment.show(supportFragmentManager, "AddressDialogFragment")
                addressDialogFragment.setOnAddressPickListener { province, city, county ->
                    mProvince = province.areaName
                    mCity = city.areaName
                    mCounty = county.areaName
                    binding.tvCity.text = "$mCity $mCounty"
                }
            }
            R.id.btn_commit -> {
                val nickname = binding.tvNickName.text.toString().trim()
                if (TextUtils.isEmpty(nickname)) {
                    ToastUtils.show("请输入昵称")
                    return
                }
                if (phone.equals(nickname)) {
                    ToastUtils.show("账号和昵称不能一致")
                    return
                }
                val photo = if (photoUrl.size > 0) photoUrl[0] else null
                if (TextUtils.isEmpty(photo)) {
                    ToastUtils.show("请选择头像")
                    return
                }
                presenter.register(phone, password, photo,
                        nickname, binding.tvSignature.text.toString().trim(), mCity, mCounty)
            }
        }
    }

    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 getLayoutResId(): Int {
        return R.layout.activity_perfect_info
    }

    override fun onLost(postcard: Postcard?) {
        Logger.e("ARouter", "丢失了")
    }

    override fun onFound(postcard: Postcard?) {
        Logger.e("ARouter", "发现了")
    }

    override fun onInterrupt(postcard: Postcard?) {
        Logger.e("ARouter", "拦截了")
    }

    override fun onArrival(postcard: Postcard?) {
        setResult(Activity.RESULT_OK)
        finish()
    }
}
