package com.abbidot.tracker.ui.activity.help

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.MMKVKey
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.MMKVUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.FeedbackImageAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.MenuTxtBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityFeedbackBinding
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.FeedbackViewModel
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
import kotlinx.coroutines.launch

/**
 * 反馈
 */
class FeedbackActivity : BaseActivity<ActivityFeedbackBinding>(ActivityFeedbackBinding::inflate) {

    private val mTakePhotoAndCompressViewModel: TakePhotoAndCompressViewModel by viewModels()
    private val mFeedbackViewModel: FeedbackViewModel by viewModels()
    private val mUserInfoViewModel: UserProfileViewModel by viewModels()

    //反馈问题类型 type 1为APP 2为设备 3其它
    private var mFeedbackType = 1

    //限制照片数量
    private val mLimitPhotoCount = 5
    private lateinit var mUploadImageUrlList: MutableList<String>

    //已上传图片的数量
    private var mUploadImageIndex = 0

    private lateinit var mFeedbackImageAdapter: FeedbackImageAdapter

    override fun getTopBar() = mViewBinding.ilSettingFeedbackBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_feedback_title)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        mUploadImageUrlList = mutableListOf()
        mFeedbackImageAdapter = FeedbackImageAdapter(mContext, this, null)

        mViewBinding.apply {
            ilFeedbackPhoneLayout.let {
                it.tvInputMustFill.visibility = View.VISIBLE
                it.tvInputNameTitle.setText(R.string.txt_enter_email_tip)
                it.etInputContent.setHint(R.string.txt_email_address)
            }

            ViewUtil.instance.setRecyclerViewHorizontalLinearLayout(
                mContext, settingFeedbackImageRv, mFeedbackImageAdapter, right = AppUtils.dpToPx(12)
            )

            radiogroupSettingFeedbackType.setOnCheckedChangeListener { _, checkedId ->
                when (checkedId) {
                    radiobuttonFeedbackAppUse.id -> {
                        mFeedbackType = 1
                    }

                    radiobuttonFeedbackProductUse.id -> {
                        mFeedbackType = 2
                    }

                    radiobuttonFeedbackProductSuggest.id -> {
                        mFeedbackType = 3
                    }
                }
            }

            setOnClickListenerViews(btnSubmitSettingFeedback, llSelectImageBtnLayout)

            setViewClickHideInputMethod(llSettingFeedbackLayout)
            setListenKeyboardChange(300, svSettingFeedbackScroll)
        }
    }

    //添加图片后，再输入邮箱，输入框被挡住
    override fun showSoftKeyboardCallback() {
        mViewBinding.apply {
            if (ilFeedbackPhoneLayout.etInputContent.hasFocus()) {
                if (mUploadImageUrlList.size > 0) svSettingFeedbackScroll.postDelayed({
                    svSettingFeedbackScroll.scrollY = 1000
                }, 400)
                else svSettingFeedbackScroll.scrollY = 500
            }
        }
    }

    override fun liveDataObserve() {
        mTakePhotoAndCompressViewModel.mPhotoPathLiveData.observe(this) {
            lifecycleScope.launch {
                val list = mutableListOf<MenuTxtBean>()
                list.addAll(mFeedbackImageAdapter.getData())
                it.forEach { file ->
                    ViewUtil.instance.addMenuBean(list, "", imageUrl = file.path)
                }
                mFeedbackImageAdapter.setData(list, true)
                mViewBinding.apply {
                    settingFeedbackImageRv.scrollToPosition(list.size - 1)
                    if (list.size == mLimitPhotoCount) {
                        setBtnUploadState(false)
                    }
                }
            }
        }

        mUserInfoViewModel.mUploadImageLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()!!
                    mUploadImageUrlList.add(data)
                    LogUtil.e("第${mUploadImageIndex + 1}张图片上传完成")
                    mUploadImageIndex++
                    uploadImageList()
                }

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

        mFeedbackViewModel.mFeedbackResultLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    showToast(R.string.txt_feedback_success, isFinish = true)
                }

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

    /**
     * 设置是否可以上传按钮状态
     */
    private fun setBtnUploadState(isCanUpload: Boolean) {
        mViewBinding.apply {
            llSelectImageBtnLayout.isEnabled = isCanUpload
            if (isCanUpload) {
                tvFeedbackChooseFileTitle.setTextColor(
                    ContextCompat.getColor(
                        mContext, R.color.data_black_color
                    )
                )
                ivFeedbackChooseFileImage.drawable.setTint(
                    ContextCompat.getColor(
                        mContext, R.color.data_black_color
                    )
                )
            } else {
                tvFeedbackChooseFileTitle.setTextColor(
                    ContextCompat.getColor(
                        mContext, R.color.gray_color10
                    )
                )
                ivFeedbackChooseFileImage.drawable.setTint(
                    ContextCompat.getColor(
                        mContext, R.color.gray_color10
                    )
                )
            }
        }
    }

    fun deletePhoto(list: MutableList<MenuTxtBean>, item: MenuTxtBean) {
        lifecycleScope.launch {
            for (i in 0 until list.size) {
                val menuTxtBean = list[i]
                if (menuTxtBean.imageUrl == item.imageUrl) {
                    list.removeAt(i)
                    mFeedbackImageAdapter.notifyItemRemoved(i)
                    setBtnUploadState(true)
                    break
                }
            }
        }
    }

    /**
     * 开始提交反馈
     */
    private fun startSubmitFeedback() {
        if (mViewBinding.radiogroupSettingFeedbackType.checkedRadioButtonId < 0) {
            showToast(R.string.txt_feedback_notype)
            return
        }
        val feedbackContent = mViewBinding.edSettingFeedbackContent.text.toString()
        val feedbackEmail = mViewBinding.ilFeedbackPhoneLayout.etInputContent.text.toString()
        if (TextUtils.isEmpty(feedbackContent) || TextUtils.isEmpty(feedbackEmail)) {
            showToast(R.string.txt_not_null)
            return
        }
        if (!Utils.isValidEmail(feedbackEmail)) {
            showToast(R.string.txt_valid_email)
            return
        }

        mUploadImageIndex = 0
        mUploadImageUrlList.clear()
        setButtonEnabled(mViewBinding.btnSubmitSettingFeedback, ConstantInt.Type0)
        uploadImageList()
    }

    /**
     * 多张图片上传
     */
    private fun uploadImageList() {
        val photoList = mFeedbackImageAdapter.getData()
        if (photoList.size > mUploadImageIndex) {
            val imageUrl = photoList[mUploadImageIndex].imageUrl
            if (TextUtils.isEmpty(imageUrl)) {
                mUploadImageIndex++
                uploadImageList()
            } else {
                mUserInfoViewModel.uploadImage(this, imageUrl)
            }
        } else {
            LogUtil.e("图片已全部上传")
            submitFeedbackOk()
        }
    }

    /**
     * 完成提交反馈
     */
    private fun submitFeedbackOk() {
        val feedbackContent = mViewBinding.edSettingFeedbackContent.text.toString()
        val feedbackEmail = mViewBinding.ilFeedbackPhoneLayout.etInputContent.text.toString()
        val userId = MMKVUtil.getString(MMKVKey.UserId)
        val imageUrls = mUploadImageUrlList.joinToString(",")
        mFeedbackViewModel.feedback(
            this, mFeedbackType, userId, feedbackContent, imageUrls, feedbackEmail
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (RESULT_OK == resultCode) {
            //相机或相册回调
            if (requestCode == ResultCode.ResultCode_1) {
                if (null != data) {
                    hideInputMethod(mViewBinding.root)
                    //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                    val resultPhotos: ArrayList<Photo> =
                        data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)!!
                    mTakePhotoAndCompressViewModel.dealCompressPhoto(mContext, resultPhotos)
                }
            }
        }
    }

    override fun onClick(v: View?) {
        if (isLimitClick()) return
        mViewBinding.apply {
            when (v!!) {
                btnSubmitSettingFeedback -> startSubmitFeedback()
                llSelectImageBtnLayout -> {
                    if (mFeedbackImageAdapter.getData().size == mLimitPhotoCount) {
                        showToast(
                            String.format(
                                getString(R.string.selector_reach_max_image_hint_easy_photos),
                                mLimitPhotoCount
                            )
                        )
                        return@apply
                    }
                    ViewUtil.instance.goSelectPhoto(
                        this@FeedbackActivity,
                        ResultCode.ResultCode_1,
                        count = mLimitPhotoCount - mFeedbackImageAdapter.getData().size
                    )
                }
            }
        }
    }
}