package com.cheng.blzb.ui.fragment.bid.publish.goods

import android.annotation.SuppressLint
import android.os.Build
import android.text.TextUtils
import android.view.ViewOutlineProvider
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.bean.MerchantGoodsEntity
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentPublishGoodsMessageBinding
import com.cheng.blzb.event.SupplyEvent
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.SelectAreaDialog
import com.cheng.blzb.ui.dialog.SelectContactsDialog
import com.cheng.blzb.ui.dialog.SelectGoodsTypeDialog
import com.cheng.blzb.ui.fragment.bid.publish.AddBidContactsAdapter
import com.cheng.blzb.ui.fragment.bid.publish.AddBidImageAdapter
import com.cheng.blzb.ui.fragment.bid.publish.my.MyPublishFragment
import com.cheng.blzb.utils.GlideEngine
import com.cheng.blzb.utils.PermissionUtils
import com.example.base.common.RxBus
import com.example.base.extensions.getColor
import com.example.base.extensions.gone
import com.example.base.extensions.invisible
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.SpanUtils
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.anko.sdk27.listeners.onTouch

class PublishGoodsMessageFragment: BaseFragment<FragmentPublishGoodsMessageBinding, PublishGoodsMessageViewModel>() {
    private val from by lazy { arguments?.getInt("from") ?: 0 }

    private var goodsDetail: MerchantGoodsEntity? = null

    private val imageAdapter by lazy { AddBidImageAdapter(requireContext(), uploadedImgList) }
    private var uploadedImgList: ArrayList<UploadFileEntity> = ArrayList()
    private val deletedList = mutableListOf<String>()

    private val contactsAdapter by lazy { AddBidContactsAdapter() }

    private var goodsType: String = "" // 1 提供服务 2 提供产品 3其他
    private var priceType: Int = 1 // 1 具体价格 2 面议

    private var city: AreaEntity? = null

    private val textWatcher = object : TextWatcherImpl() {
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            super.onTextChanged(s, start, before, count)
            SpanUtils.with(binding.tvTextCount)
                .append("${s?.length ?: 0}")
                .setForegroundColor(getColor(R.color.color_1a1a1a))
                .append("/500")
                .create()
        }
    }

    override fun initView() {
        super.initView()
        binding.tvDesc.typeface = Constants.dtjbt

        imageAdapter.selectMax = 5
        binding.rvImages.adapter = imageAdapter
        binding.rvContacts.adapter = contactsAdapter

        binding.ivTopBg.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val lp1 = binding.tvDesc.layoutParams as ConstraintLayout.LayoutParams
                lp1.topMargin = (binding.ivTopBg.height * 100f / 314f).toInt()
                binding.tvDesc.layoutParams = lp1

                val lp2 = binding.layoutContent.layoutParams as ConstraintLayout.LayoutParams
                lp2.topMargin = (binding.ivTopBg.height * 168f / 314f).toInt()
                binding.layoutContent.layoutParams = lp2

                binding.layoutContent.setupWith(binding.layoutContainer).setFrameClearDrawable(binding.layoutContent.background).setBlurRadius(5f)
                binding.layoutContent.outlineProvider = ViewOutlineProvider.BACKGROUND
                binding.layoutContent.setClipToOutline(true)

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

    override fun initData() {
        super.initData()
        goodsDetail = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("item", MerchantGoodsEntity::class.java)
        } else {
            arguments?.getSerializable("item") as? MerchantGoodsEntity
        }
        if (goodsDetail != null) {
            setData(goodsDetail!!)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()
        binding.etExplain.addTextChangedListener(textWatcher)

        binding.tvType.onClick {
            val f = SelectGoodsTypeDialog.newInstance(goodsType)
            f.setOnSelectListener {
                goodsType = it.id
                binding.tvType.text = it.name
            }
            f.show(childFragmentManager, "")
        }

        binding.tvArea.onClick {
            val f = SelectAreaDialog.newInstance(if (city != null) listOf(city!!) else emptyList(), true)
            f.setOnSelectListener {
                city = it[0]
                binding.tvArea.text = city!!.name
            }
            f.show(childFragmentManager, SelectAreaDialog::class.java.simpleName)
        }

        binding.ivAddContacts.onClick {
            val f = SelectContactsDialog.newInstance(contactsAdapter.data)
            f.setOnSelectListener {
                contactsAdapter.setList(it)
                binding.rvContacts.visible()
                binding.tvContacts.gone()
            }
            f.show(childFragmentManager, "")
        }

        binding.tvContacts.onClick {
            binding.ivAddContacts.performClick()
        }

        binding.rvContacts.onTouch { _, _ ->
            binding.ivAddContacts.performClick()
            true
        }

        binding.tvPrice1.onClick {
            binding.rbPrice1.isChecked = true
        }

        binding.tvPrice2.onClick {
            binding.rbPrice2.isChecked = true
        }

        binding.rgPriceType.setOnCheckedChangeListener { _, checkedId ->
            when(checkedId) {
                R.id.rb_price1 -> {
                    priceType = 1
                    binding.etPrice.setText("")
                    binding.etPrice.isEnabled = true
                    binding.tvUnit.visible()
                }
                R.id.rb_price2 -> {
                    priceType = 2
                    binding.etPrice.setText("面议")
                    binding.etPrice.isEnabled = false
                    binding.tvUnit.gone()
                }
            }
        }

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

                AddBidImageAdapter.TYPE_DELETE -> {
                    if (uploadedImgList.isNotEmpty()) {
                        if (goodsDetail == null) {
                            mViewModel.deleteFile(imageAdapter.data[position].id)
                        }
                        deletedList.add(uploadedImgList[position].id)
                        uploadedImgList.removeAt(position)
                        imageAdapter.notifyDataSetChanged()
                        SpanUtils.with(binding.tvImageCount)
                            .append("(")
                            .append("${uploadedImgList.size}")
                            .setForegroundColor(getColor(R.color.color_ff493c))
                            .append("/5)")
                            .create()
                    }
                }
            }
        }

        binding.btnNext.onClick {
            val name = binding.etName.text.toString().trim()
            val price = binding.etPrice.text.toString().trim()
            val desc = binding.etExplain.text.toString().trim()
            if (TextUtils.isEmpty(name)) {
                toast("请输入名称")
                return@onClick
            }
            if (priceType == 1 && TextUtils.isEmpty(price)) {
                toast("请输入价格")
                return@onClick
            }
            if (city == null) {
                toast("请选择地区")
                return@onClick
            }
            if (TextUtils.isEmpty(desc)) {
                toast("请输入说明")
                return@onClick
            }
            if (imageAdapter.data.isEmpty()) {
                toast("请上传宣传图")
                return@onClick
            }
            if (contactsAdapter.data.isEmpty()) {
                toast("请添加联系人")
                return@onClick
            }
            commit()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initObserve() {
        super.initObserve()
        mViewModel.addLiveData.observe(this) {
            toast("提交成功")
            RxBus.defaultInstance.post(SupplyEvent(from))
            if (from == 1) {
                PublicActivity.start(requireContext(), MyPublishFragment::class.java, Pair("type", 2))
            }
            requireActivity().finish()
        }

        mViewModel.imageLiveData.observe(this) {
            uploadedImgList.addAll(it)
            imageAdapter.notifyDataSetChanged()
            SpanUtils.with(binding.tvImageCount)
                .append("(")
                .append("${uploadedImgList.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5)")
                .create()
        }
    }

    private fun commit() {
        val name = binding.etName.text.toString().trim()
        val price = binding.etPrice.text.toString().trim()
        val desc = binding.etExplain.text.toString().trim()
        val jsonObject = JsonObject()
        jsonObject.addProperty("type", "$goodsType")
        jsonObject.addProperty("goods_name", name)
        jsonObject.addProperty("goods_price", price)
        jsonObject.addProperty("goods_price_type", "$priceType")
        jsonObject.addProperty("goods_description", desc)
        jsonObject.addProperty("city_id", "${city!!.id}")

        val imageArray = JsonArray()
        uploadedImgList.forEach {
            imageArray.add(it.id)
        }
        jsonObject.add("file", imageArray)

        val contactArray = JsonArray()
        contactsAdapter.data.forEach {
            val contactObj = JsonObject()
            contactObj.addProperty("name", it.name)
            contactObj.addProperty("phone", it.phone)
            contactObj.addProperty("job", it.job)
            contactArray.add(contactObj)
        }
        jsonObject.add("contact", contactArray)

        if (goodsDetail == null) {
            mViewModel.addGoods(jsonObject.toString().toRequestBody())
        } else {
            jsonObject.addProperty("id", goodsDetail!!.id)
            mViewModel.updateGoods(jsonObject.toString().toRequestBody())
        }
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    private fun setData(detail: MerchantGoodsEntity) {
        if (detail.status == "3") {
            binding.tvReason.text = "理由：${detail.remark}"
            binding.tvTime.text = detail.review_time
            binding.layoutRejectReason.visible()
        }
        goodsType = detail.type
        binding.tvType.text = if (detail.type == "1") "提供服务" else if (detail.type == "2") "提供产品" else "其他"
        binding.rgPriceType.check(if (detail.goods_price_type == "1") R.id.rb_price1 else R.id.rb_price2)
        binding.etName.setText(detail.goods_name)
        binding.etPrice.setText(detail.goods_price)
        binding.etExplain.setText(detail.goods_description)

        city = UserConfigManager.getCityList().find { it.id == detail.city_id.toInt() }
        if (city != null) binding.tvArea.text = city!!.name

        val imageList = Gson().fromJson<List<UploadFileEntity>>(Gson().toJson(detail.file), object : TypeToken<List<UploadFileEntity>>(){}.type)
        uploadedImgList.addAll(imageList)
        imageAdapter.notifyDataSetChanged()
        SpanUtils.with(binding.tvImageCount)
            .append("(")
            .append("${uploadedImgList.size}")
            .setForegroundColor(getColor(R.color.color_ff493c))
            .append("/5)")
            .create()

        contactsAdapter.setList(detail.contact)
        if (contactsAdapter.data.isNotEmpty()) {
            binding.rvContacts.visible()
            binding.tvContacts.gone()
        }
        if (contactsAdapter.data.size == 5) {
            binding.ivAddContacts.gone()
        }
    }

    private fun selectPhoto() {
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())
            .setFileProviderAuthority(Constants.AppFilter)
            .setCount(imageAdapter.selectMax - uploadedImgList.size)
            .start(object : SelectCallback() {
                @SuppressLint("NotifyDataSetChanged")
                override fun onResult(photos: ArrayList<Photo>, isOriginal: Boolean) {
                    if (photos.find { it.size > 10 * 1024 * 1024 } != null) {
                        toast("单张图片大小不能超过10M")
                        return
                    }
                    mViewModel.imgList.clear()
                    mViewModel.upload(requireContext(), photos)
                }

                override fun onCancel() {
                }
            })
    }

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