package com.abbidot.tracker.ui.activity.account

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import coil.load
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityUserProfileBinding
import com.abbidot.tracker.ui.common.CountryCommon
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.TakePhotoAndCompressViewModel
import com.abbidot.tracker.vm.UserProfileViewModel
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo

class UserProfileActivity :
    BaseActivity<ActivityUserProfileBinding>(ActivityUserProfileBinding::inflate) {

    private val mUserViewModel: UserProfileViewModel by viewModels()
    private val mTakePhotoAndCompressViewModel: TakePhotoAndCompressViewModel by viewModels()

    private lateinit var mCountryCommon: CountryCommon

    //上传成功头像
    private var mUploadImageUrl = ""
    private var mTempHeadPath = ""

    override fun getTopBar() = mViewBinding.ilUserProfileTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_pet_profile)
//        mRightImageButton = addRightImageButton(R.drawable.icon_gray_delete_svg)
        mViewBinding.apply {
            root.setBackgroundResource(R.color.white)

            ilUserProfileNameLayout.let {
                it.tvInputNameTitle.text = getString(R.string.register_txt_name)
                it.rlEtInputLayout.setBackgroundResource(R.drawable.shape12_gray_border_white_bg)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
                it.ivInputRepresentImage.setImageResource(R.drawable.ico_list_next)
//                ViewUtil.instance.setInputViewErrorHideClick(
//                    mContext, it.rlEtInputLayout, tvUserProfileNameErrorTip, it.etInputContent
//                )
            }
            ilUserProfileCountry.let {
                it.tvInputNameTitle.text = getString(R.string.txt_country)
                it.rlEtInputLayout.setBackgroundResource(R.drawable.shape12_gray_border_white_bg)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
                it.ivInputRepresentImage.setImageResource(R.drawable.ico_list_next)
//                ViewUtil.instance.setInputViewErrorHideClick(
//                    mContext,
//                    it.rlEtInputLayout,
//                    tvUserProfileSelectCountryErrorTip,
//                    it.etInputContent
//                )
            }
            ilUserProfileEmailLayout.let {
                it.tvInputNameTitle.text = getString(R.string.txt_email_address)
                it.rlEtInputLayout.setBackgroundResource(R.drawable.shape12_gray_border_white_bg)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
                it.ivInputRepresentImage.setImageResource(R.drawable.ico_list_next)
//                it.etInputContent.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
//                ViewUtil.instance.setInputViewErrorHideClick(
//                    mContext, it.rlEtInputLayout, tvUserProfileEmailErrorTip, it.etInputContent
//                )
            }

            mCountryCommon =
                CountryCommon(mContext, object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        ilUserProfileCountry.etInputContent.setText(mCountryCommon.getCountry())
                        userProfileSave()
                    }
                })

            setOnClickListenerViews(
                btnUserProfileSave,
                ilUserProfileHeadLayout.ilPetProfileHead.appHeadImage,
                ilUserProfileNameLayout.rlEtInputLayout,
                ilUserProfileNameLayout.ivInputRepresentImage,
                ilUserProfileCountry.rlEtInputLayout,
                ilUserProfileCountry.ivInputRepresentImage,
                ilUserProfileEmailLayout.rlEtInputLayout,
                ilUserProfileEmailLayout.ivInputRepresentImage
            )

            mUploadImageUrl = MMKVUtil.getString(MMKVKey.HeadUrl)
            ViewUtil.instance.imageLoadUrl(
                ilUserProfileHeadLayout.ilPetProfileHead.appHeadImage,
                mUploadImageUrl,
                R.drawable.pic_avatar_df
            )
        }

        mTakePhotoAndCompressViewModel.registerCropImageActivityResult(this)

//        mUserViewModel.getCountryCodes(this)
        mUserViewModel.getUserInfo(this@UserProfileActivity)
    }

    override fun onResume() {
        super.onResume()
        mViewBinding.apply {
            val username = MMKVUtil.getString(MMKVKey.UserName)
            val email = MMKVUtil.getString(MMKVKey.Email)
            ilUserProfileNameLayout.etInputContent.setText(username)
            ilUserProfileEmailLayout.etInputContent.setText(email)
        }
    }

    override fun liveDataObserve() {
        mUserViewModel.apply {
            //获取国家代码
//            mCountryCodeLiveData.observe(this@UserProfileActivity) {
//                getUserInfo(this@UserProfileActivity)
//                dealRequestResult(it, object : GetResultCallback {
//                    override fun onResult(any: Any) {
//                        it.getOrNull()?.apply {
//                            mCountryCommon.setCountryCodeData(this)
//                            val countryCode = MMKVUtil.getString(MMKVKey.CountryCode)
//                            val country = mCountryCommon.codeToCountry(countryCode)
//                            mViewBinding.ilUserProfileCountry.etInputContent.setText(country)
//                        }
//                    }
//                })
//            }
            //获取用户信息
            mUserInfoLiveData.observe(this@UserProfileActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { info ->
                            mViewBinding.ilUserProfileNameLayout.etInputContent.setText(info.userName)
                            mViewBinding.ilUserProfileEmailLayout.etInputContent.setText(info.email)
                            mUploadImageUrl = info.imgurl
                            ViewUtil.instance.imageLoadUrl(
                                mViewBinding.ilUserProfileHeadLayout.ilPetProfileHead.appHeadImage,
                                mUploadImageUrl,
                                R.drawable.pic_avatar_df
                            )
                        }
                    }
                })
            }

            //上传头像
            mUploadImageLiveData.observe(this@UserProfileActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        val data = it.getOrNull()
//                        showToast(R.string.txt_upload_successful)
                        mUploadImageUrl = data!!
                        mViewBinding.ilUserProfileHeadLayout.ilPetProfileHead.appHeadImage.load(
                            mUploadImageUrl
                        )
                        userProfileSave()
                    }
                })
            }

            mUpdateUserInfoLiveData.observe(this@UserProfileActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        XEventBus.post(EventName.UpdateUserInfo)
                        showToast(R.string.txt_change_successful)
                    }
                })
            }

//            mUserLogoffLiveData.observe(this@UserProfileActivity) {
//                dealRequestResult(it, object : GetResultCallback {
//                    override fun onResult(any: Any) {
//                        Util.logOut(this@UserProfileActivity, lifecycleScope)
//                    }
//                })
//            }
        }
        mTakePhotoAndCompressViewModel.mPhotoPathLiveData.observe(this) {
            if (it.size > 0) {
                mTempHeadPath = it[0].path
//                mViewBinding.ilUserProfileHeadLayout.ilPetProfileHead.appHeadImage.load(it[0])
                mUserViewModel.uploadImage(this@UserProfileActivity, mTempHeadPath)
            }
        }
//        XEventBus.observe(this, EventName.UpdateUserInfo) {
//            val email = MMKVUtil.getString(MMKVKey.Email)
//            mViewBinding.ilUserProfileEmailLayout.etInputContent.setText(email)
//        }
    }

//    /**
//     * 注销账户
//     */
//    private fun closeAccount() {
//        ViewUtil.instance.showDialog(
//            mContext, R.string.txt_close_account_tips, object : BaseDialog.OnOkClickListener {
//                override fun onOkClick(dialog: BaseDialog<*>) {
//                    dialog.dismiss()
//                    mUserViewModel.logoff(this@UserProfileActivity)
//                }
//            }, okTextResId = R.string.txt_sure
//        )
//    }

    private fun userProfileSave() {
        mViewBinding.apply {
            val name = ilUserProfileNameLayout.etInputContent.text.toString()
//            val country = ilUserProfileCountry.etInputContent.text.toString()
            val email = ilUserProfileEmailLayout.etInputContent.text.toString()
            var isSure = true
            if (TextUtils.isEmpty(name)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilUserProfileNameLayout.rlEtInputLayout, tvUserProfileNameErrorTip
                )
            }
//            if (TextUtils.isEmpty(country)) {
//                isSure = false
//                ViewUtil.instance.setInputViewErrorShow(
//                    mContext,
//                    ilUserProfileCountry.rlEtInputLayout,
//                    tvUserProfileSelectCountryErrorTip
//                )
//            }
            if (TextUtils.isEmpty(email) || !Utils.isValidEmail(email)) {
                isSure = false
                ViewUtil.instance.setInputViewErrorShow(
                    mContext, ilUserProfileEmailLayout.rlEtInputLayout, tvUserProfileEmailErrorTip
                )
            }
            if (!isSure) return

            mUserViewModel.updateUserInfo(
                this@UserProfileActivity, "", mUploadImageUrl, mCountryCommon.getCountryCode(), name
            )
        }
    }

    private fun dealPhoto(data: Intent?) {
        if (null != data) {
            //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
            val resultPhotos: ArrayList<Photo>? =
                data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)
            //返回图片地址集合时如果你需要知道用户选择图片时是否选择了原图选项，用如下方法获取
//                data.getBooleanExtra(EasyPhotos.RESULT_SELECTED_ORIGINAL, false)
            mTakePhotoAndCompressViewModel.goCropAndCompressImage(resultPhotos)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (RESULT_OK == resultCode) {
            //相机或相册回调
            if (requestCode == ResultCode.ResultCode_1) {
                dealPhoto(data)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilUserProfileCountry.rlEtInputLayout, ilUserProfileCountry.ivInputRepresentImage -> mCountryCommon.showCountryCodeDialog()
                ilUserProfileEmailLayout.rlEtInputLayout, ilUserProfileEmailLayout.ivInputRepresentImage -> Intent(
                    mContext, EmailAddressActivity::class.java
                ).let {
                    startActivity(it)
                }

                ilUserProfileNameLayout.rlEtInputLayout, ilUserProfileNameLayout.ivInputRepresentImage -> Intent(
                    mContext, ChangeNameActivity::class.java
                ).let {
                    startActivity(it)
                }

                btnUserProfileSave -> {
                    if (TextUtils.isEmpty(mTempHeadPath)) {
                        userProfileSave()
                    } else {
                        mUserViewModel.uploadImage(this@UserProfileActivity, mTempHeadPath)
                    }
                }

                ilUserProfileHeadLayout.ilPetProfileHead.appHeadImage -> ViewUtil.instance.goSelectPhoto(
                    this@UserProfileActivity, ResultCode.ResultCode_1
                )

//                mRightImageButton -> closeAccount()
            }
        }
    }
}