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

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.cheng.blzb.R
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentFeedbackBinding
import com.cheng.blzb.ui.fragment.photo.AddImageAdapter
import com.cheng.blzb.utils.PermissionUtils
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 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<UploadFileEntity> = ArrayList()
    private var deletedImg: ArrayList<UploadFileEntity> = 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.tvTitle.typeface = Constants.pmzdbt

        binding.etFeedbackContent.addTextChangedListener(textWatcher)

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

        binding.mTitleBar.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val lp = binding.tvTitle.layoutParams as ConstraintLayout.LayoutParams
                lp.topMargin = binding.mTitleBar.height
                binding.tvTitle.layoutParams = lp

                binding.mTitleBar.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    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.isNotEmpty()) {
                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.blzb.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?) {

        }

    }
}