package com.cheng.bole.ui.fragment.mine.feedback

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.recyclerview.widget.GridLayoutManager
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.ui.BaseFragment
import com.google.gson.JsonArray
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.bole.R
import com.cheng.bole.common.Constants
import com.cheng.bole.databinding.FragmentFeedbackBinding
import com.cheng.bole.ui.fragment.photo.AddImageAdapter
import com.cheng.bole.utils.PermissionUtils
import okhttp3.RequestBody.Companion.toRequestBody

class FeedbackFragment : BaseFragment<FragmentFeedbackBinding, FeedbackViewModel>() {
    private var type = TYPE_SUGGESTION

    private val imageAdapter by lazy { AddImageAdapter(requireContext(), selectedPhotoList) }
    private var selectedPhotoList: ArrayList<Photo> = ArrayList()
    private var selectImg: ArrayList<com.cheng.bole.bean.UploadImgEntity> = ArrayList()
    private var deletedImg: ArrayList<com.cheng.bole.bean.UploadImgEntity> = ArrayList()

    companion object {
        const val TYPE_SUGGESTION = 0
        const val TYPE_BUG = 1
        const val TYPE_OTHER = 2
    }

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

        binding.etFeedbackContent.addTextChangedListener(textWatcher)

        binding.rvImage.layoutManager = GridLayoutManager(context, 3)
        imageAdapter.selectMax = 3
        binding.rvImage.adapter = imageAdapter
    }

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

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()
        binding.rgFeedbackType.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rg_1 -> type = TYPE_SUGGESTION
                R.id.rg_2 -> type = TYPE_BUG
                R.id.rg_3 -> type = TYPE_OTHER
            }
        }
        binding.btnNext.onClick {
            val content = binding.etFeedbackContent.text?.trim().toString()
            if (TextUtils.isEmpty(content)) {
                toast("请输入详情内容")
                return@onClick
            }
            if (selectImg.isEmpty() && selectedPhotoList.size > 0) {
                mViewModel.upload(requireContext(), selectedPhotoList)
            } else {
                commit()
            }
        }

        imageAdapter.setOnItemClick { type, position ->
            when (type) {
                AddImageAdapter.TYPE_ADD -> {
                    PermissionUtils.checkPhotoPermission(requireActivity(), childFragmentManager, true) {
                        if (it) selectPhoto()
                    }
                }

                AddImageAdapter.TYPE_DELETE -> {
                    if (selectImg.isNotEmpty() && selectImg.size == imageAdapter.data.size) {
                        deletedImg.add(selectImg[position])
                        selectImg.removeAt(position)
                    }
                    if (selectedPhotoList.isNotEmpty()) {
                        selectedPhotoList.removeAt(position)
                        imageAdapter.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.feedbackLiveData.observe(this) {
            toast("反馈成功")
            requireActivity().finish()
        }
        mViewModel.uploadSuccessLiveData.observe(this) {
            selectImg.addAll(it)
            mViewModel.delete(deletedImg)
            commit()
        }
    }

    private fun commit() {
        var typeStr = if (type == TYPE_SUGGESTION) "产品建议" else if (type == TYPE_BUG) "功能异常" else "其他问题"
        if (!TextUtils.isEmpty(arguments?.getString("text"))) {
            typeStr += "(${arguments?.getString("text")})"
        }
        val content = binding.etFeedbackContent.text?.trim().toString()
        val contactInfo = binding.etContactInfo.text?.trim().toString()
        val jsonObject = JsonObject()
        jsonObject.addProperty("type", typeStr)
        jsonObject.addProperty("content", content)
        jsonObject.addProperty("contact", contactInfo)
        val imageArray = JsonArray()
        selectImg.forEach {
            imageArray.add(it.url)
        }
        jsonObject.add("images", imageArray)
        mViewModel.feedback(jsonObject.toString().toRequestBody())
    }

    override fun onDestroyView() {
        binding.etFeedbackContent.removeTextChangedListener(textWatcher)
        super.onDestroyView()
    }

    private fun selectPhoto() {
        EasyPhotos.createAlbum(this, true, false, com.cheng.bole.utils.GlideEngine.getInstance())
            .setFileProviderAuthority(Constants.AppFilter)
            .setCount(imageAdapter.selectMax - selectedPhotoList.size)
            .start(object : SelectCallback() {
                @SuppressLint("NotifyDataSetChanged")
                override fun onResult(photos: ArrayList<Photo>, isOriginal: Boolean) {
                    selectedPhotoList.addAll(photos)
                    imageAdapter.notifyDataSetChanged()
                }

                override fun onCancel() {
                }
            })
    }

    private val textWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        @SuppressLint("SetTextI18n")
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            binding.tvTextCount.text = "${s?.length}/200"
        }

        override fun afterTextChanged(s: Editable?) {

        }

    }
}