package com.abbidot.tracker.ui.activity.pet.first

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
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.util.MMKVUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityFirstPetProfileBinding
import com.abbidot.tracker.ui.activity.device.wifi.AddWifiPowerZone1Activity
import com.abbidot.tracker.ui.common.PetProfileCommon
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.PetInfoViewModel
import com.abbidot.tracker.vm.PetRelationViewModel
import com.abbidot.tracker.vm.TakePhotoAndCompressViewModel
import com.abbidot.tracker.vm.TrackerInfoViewModel
import com.abbidot.tracker.vm.UserProfileViewModel
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FirstPetProfileActivity :
    BaseActivity<ActivityFirstPetProfileBinding>(ActivityFirstPetProfileBinding::inflate),
    BaseDialog.OnDialogOkListener {

    private val mPetViewModel: PetInfoViewModel by viewModels()
    private val mTrackerViewModel: TrackerInfoViewModel by viewModels()
    private val mPetRelationViewModel: PetRelationViewModel by viewModels()
    private val mTakePhotoAndCompressViewModel: TakePhotoAndCompressViewModel by viewModels()
    private val mUserInfoViewModel: UserProfileViewModel by viewModels()

    private var isFirstBind = false
    private var mPetBean: PetBean? = null

    //选取头像本地路径
    private var mSelectPetHeadPath = ""

    private lateinit var mProfileCommon: PetProfileCommon

    override fun getTopBar() = mViewBinding.ilFirstPetProfileTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
        }

        mViewBinding.apply {
            root.setBackgroundResource(R.color.white)

            mProfileCommon = PetProfileCommon(mContext, rvFirstPetProfileLabel, mPetBean)

            ViewUtil.instance.setPetTypeHead(
                ilFirstPetProfileHeadLayout.ilPetProfileHead.appHeadImage, "", 1
            )
            mPetBean?.apply {
                tvFirstPetProfilePetName.text = petName
                ViewUtil.instance.setPetTypeHead(
                    ilFirstPetProfileHeadLayout.ilPetProfileHead.appHeadImage, imgurl, petType
                )
            }

            ilFirstPetProfileBreed.let {
                it.tvInputNameTitle.text = getString(R.string.acccount_breed)
            }
            ilFirstPetProfileBirthday.let {
                it.tvInputNameTitle.text = getString(R.string.acccount_birthday)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
                it.ivInputRepresentImage.setImageResource(R.drawable.icon_profile_birthday_edit_svg)
            }
            ilFirstPetProfileSex.let {
                it.tvInputNameTitle.text = getString(R.string.txt_sex)
                ViewUtil.instance.setEditTextDropSelectState(it.etInputContent)
                it.ivInputRepresentImage.visibility = View.VISIBLE
            }

            mProfileCommon.setSexListData(ilFirstPetProfileSex.etInputContent)

            setOnClickListenerViews(
                rlFirstPetProfileLabels,
                ilFirstPetProfileBirthday.root,
                ilFirstPetProfileSex.root,
                ilFirstPetProfileHeadLayout.ilPetProfileHead.appHeadImage,
                btnFirstPetProfileNext,
                tvFirstPetProfileLaterBtn
            )
        }

        mTakePhotoAndCompressViewModel.registerCropImageActivityResult(this)

        mPetViewModel.getPetLabels(this)
    }

    override fun liveDataObserve() {
        //获取设备列表,方便把设备保存到本地
        mTrackerViewModel.getDeviceListLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.let { list ->
                        lifecycleScope.launch {
                            withContext(Dispatchers.IO) {
                                for (device in list) {
                                    //保存本地数据库
                                    if (!TextUtils.isEmpty(device.deviceOutId) && null != device.pet) {
                                        MyDatabase.deviceDao().insert(device)
                                    }
                                }
                            }
                        }
                    }

                    showToast(R.string.txt_bind_success, isFinish = true)
                    mViewBinding.root.postDelayed({
                        MMKVUtil.putInt(MMKVKey.isBindPet, ConstantInt.isBind)
                        mPetBean?.apply {
                            val intent = Intent(mContext, AddWifiPowerZone1Activity::class.java)
                            intent.putExtra(ConstantString.Pet, this)
                            intent.putExtra(ConstantString.isFirstBind, isFirstBind)
                            startActivity(intent)
                        }
                    }, 1500)
                }
            })
        }

        //设备绑定宠物
        mPetRelationViewModel.mBindPetLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    XEventBus.post(EventName.RefreshPet)
                    mTrackerViewModel.getDeviceList(this@FirstPetProfileActivity, 1)
                }

                override fun onRequestError(exceptionCode: String?) {
                    super.onRequestError(exceptionCode)
                    setButtonEnabled(mViewBinding.tvFirstPetProfileLaterBtn, ConstantInt.Type1)
                    setButtonEnabled(mViewBinding.btnFirstPetProfileNext, ConstantInt.Type1)
                }
            })
        }

        mPetViewModel.apply {
            //获取宠物标签
            mPetLabelsLiveData.observe(this@FirstPetProfileActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { labels ->
                            mProfileCommon.getLabelData(labels)
                        }
                    }
                })
            }
            //添加宠物
            mAddPetLiveData.observe(this@FirstPetProfileActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        it.getOrNull()?.let { pet ->
                            mPetBean?.let { petBean ->
                                petBean.petId = pet.petId
                                mPetRelationViewModel.bindPet(
                                    this@FirstPetProfileActivity, petBean.deviceId, petBean.petId
                                )
                            }
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        setButtonEnabled(mViewBinding.tvFirstPetProfileLaterBtn, ConstantInt.Type1)
                        setButtonEnabled(mViewBinding.btnFirstPetProfileNext, ConstantInt.Type1)
                    }
                })
            }
        }
        //选取照片
        mTakePhotoAndCompressViewModel.mPhotoPathLiveData.observe(this) {
            if (it.size > 0) {
                mSelectPetHeadPath = it[0].path
                mViewBinding.ilFirstPetProfileHeadLayout.ilPetProfileHead.appHeadImage.load(it[0])
            }
        }

        //上传照片
        mUserInfoViewModel.mUploadImageLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
//                        showToast(R.string.txt_upload_successful)
                        mPetBean?.let { pet ->
                            pet.imgurl = this
                            mPetViewModel.addPet(this@FirstPetProfileActivity, pet)
                        }
                    }
                }
            })
        }
    }


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

    override fun onOkClick(dialog: BaseDialog<*>) {
        dialog.dismiss()
        mViewBinding.apply {
            mProfileCommon.showSelectPetLabels(tvFirstPetProfileLabelTitle, svFirstPetProfile)
        }
    }

    private fun saveProfile() {
        mViewBinding.apply {
            val breed = ilFirstPetProfileBreed.etInputContent.text.toString()
            val birthday = ilFirstPetProfileBirthday.etInputContent.text.toString()
            val sex = ilFirstPetProfileSex.etInputContent.text.toString()
            if (TextUtils.isEmpty(birthday) || TextUtils.isEmpty(sex)) {
                showToast(R.string.txt_not_null)
                return
            }
            setButtonEnabled(btnFirstPetProfileNext, ConstantInt.Type0)
            mPetBean?.let {
                it.breed = breed
            }

            addPet()
        }
    }

    private fun addPet() {
        setButtonEnabled(mViewBinding.tvFirstPetProfileLaterBtn, ConstantInt.Type0)
        setButtonEnabled(mViewBinding.btnFirstPetProfileNext, ConstantInt.Type0)
        if (TextUtils.isEmpty(mSelectPetHeadPath)) {
            mPetBean?.apply {
                mPetViewModel.addPet(this@FirstPetProfileActivity, this)
            }
        } else {
            mUserInfoViewModel.uploadImage(this@FirstPetProfileActivity, mSelectPetHeadPath)
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilFirstPetProfileHeadLayout.ilPetProfileHead.appHeadImage -> ViewUtil.instance.goSelectPhoto(
                    this@FirstPetProfileActivity, ResultCode.ResultCode_1
                )

                rlFirstPetProfileLabels -> mProfileCommon.showLabelDialog(this@FirstPetProfileActivity)

                ilFirstPetProfileBirthday.root -> mProfileCommon.showBirthdayDialog(mViewBinding.ilFirstPetProfileBirthday.etInputContent)

                ilFirstPetProfileSex.root -> mProfileCommon.showSexDialog()

                btnFirstPetProfileNext -> saveProfile()
                tvFirstPetProfileLaterBtn -> addPet()
            }
        }
    }
}