package com.cheng.blzb.ui.fragment.mine.user

import android.annotation.SuppressLint
import android.text.TextUtils
import coil.load
import coil.transform.CircleCropTransformation
import com.example.base.common.RxBus
import com.example.base.extensions.getColor
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.ui.BaseFragment
import com.google.gson.JsonObject
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.cheng.blzb.R
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.bean.UserEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentUserSettingBinding
import com.cheng.blzb.event.UserInfoEvent
import com.cheng.blzb.ui.dialog.EditTextDialog
import com.cheng.blzb.utils.PermissionUtils
import okhttp3.RequestBody.Companion.toRequestBody

class UserSettingFragment : BaseFragment<FragmentUserSettingBinding, UserSettingViewModel>() {
    private var userInfo: UserEntity? = null
    private var selectedPhoto: Photo? = null
    private var selectedImg: UploadFileEntity? = null

    override fun initView() {
        super.initView()
        mTitleBar?.background = null
    }

    override fun initData() {
        super.initData()
        mViewModel.userInfo()
    }

    override fun initListener() {
        super.initListener()
        binding.ivAvatar.onClick {
            PermissionUtils.checkPhotoPermission(requireActivity(), childFragmentManager, true) {
                if (it) selectPhoto()
            }
        }
        binding.tvUsername.onClick {
            val f = EditTextDialog.newInstance("编辑昵称", binding.tvUsername.text.toString())
            f.setOnTextListener {
                if (it.length > 20) {
                    toast("昵称不能超过20个字")
                    return@setOnTextListener
                }
                binding.tvUsername.text = it
            }
            f.show(childFragmentManager, EditTextDialog::class.java.simpleName)
        }
        binding.tvSave.onClick {
            val username = binding.tvUsername.text.toString()
            if (TextUtils.isEmpty(username)) {
                toast("请输入您的昵称")
                return@onClick
            }
            if (selectedPhoto != null) {
                mViewModel.uploadImg(requireContext(), selectedPhoto!!)
            } else {
                commit()
            }
        }
    }

    private fun commit() {
        val username = binding.tvUsername.text.toString()
        if (TextUtils.isEmpty(username)) {
            toast("请输入您的昵称")
            return
        }
        val jsonObject = JsonObject()
        if (selectedImg != null) {
            jsonObject.addProperty("avater", selectedImg!!.url)
        }
        jsonObject.addProperty("name", username)
        mViewModel.updateUserinfo(jsonObject.toString().toRequestBody())
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.userInfoLiveData.observe(this) {
            userInfo = it
            setUserInfo()
        }
        mViewModel.uploadUserinfoLiveData.observe(this) {
            toast("修改成功")
            RxBus.defaultInstance.post(UserInfoEvent())
            requireActivity().finish()
        }
        mViewModel.uploadImgLiveData.observe(this) {
            selectedImg = it
            commit()
        }
        val userinfoEvent = RxBus.defaultInstance.toObservable(UserInfoEvent::class.java).subscribe {
            mViewModel.userInfo()
        }
        addDisposable(userinfoEvent)
    }

    @SuppressLint("SetTextI18n")
    private fun setUserInfo() {
        binding.ivAvatar.load(userInfo?.avater) {
            transformations(CircleCropTransformation())
            placeholder(R.mipmap.ic_default_avatar)
            error(R.mipmap.ic_default_avatar)
        }
        if (userInfo?.vip == "1") {
            binding.tvVip.text = "非会员"
            binding.tvVip.setTextColor(getColor(R.color.color_999999))
        } else if (userInfo?.vip == "2") {
            binding.tvVip.text = "${userInfo?.vip_expire} 到期"
            binding.tvVip.setTextColor(getColor(R.color.color_212226))
        } else if (userInfo?.vip == "3") {
            binding.tvVip.text = "终生会员"
            binding.tvVip.setTextColor(getColor(R.color.color_212226))
        }
        binding.tvUsername.text = userInfo?.name
    }

    private fun selectPhoto() {
        EasyPhotos.createAlbum(this, true, false, com.cheng.blzb.utils.GlideEngine.getInstance())
            .setFileProviderAuthority(Constants.AppFilter)
            .setCount(1)
            .start(object : SelectCallback() {
                override fun onResult(photos: ArrayList<Photo>, isOriginal: Boolean) {
                    if (photos.isNotEmpty()) {
                        selectedPhoto = photos[0]
                    }
                }

                override fun onCancel() {
                }
            })
    }
}