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

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.TextUtils
import android.view.ViewTreeObserver
import androidx.activity.result.contract.ActivityResultContracts
import androidx.constraintlayout.widget.ConstraintLayout
import coil.load
import coil.transform.RoundedCornersTransformation
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.bean.CompanyEntity
import com.cheng.blzb.bean.UploadFileEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentCompanyAuthBinding
import com.cheng.blzb.event.CompanyAuthEvent
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.fragment.bid.publish.AddBidContactsAdapter
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.ui.fragment.photo.PhotoViewFragment
import com.cheng.blzb.utils.FileProviderUtils
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.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.anko.sdk27.listeners.onTouch

class CompanyAuthFragment : BaseFragment<FragmentCompanyAuthBinding, CompanyAuthViewModel>() {
    private var companyDetail: CompanyEntity? = null

    private var image: UploadFileEntity? = null

    private val contactsAdapter by lazy { AddBidContactsAdapter() }

    private var city: AreaEntity? = null

    private val imageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.let {
            val imagePath = FileProviderUtils.getFileAbsolutePath(requireContext(), it)
            if (!TextUtils.isEmpty(imagePath)) {
                mViewModel.uploadImage(requireContext(), imagePath!!)
            } else {
                toast("图片加载失败")
            }
        }
    }

    override fun initView() {
        super.initView()
        binding.tvTitle.typeface = Constants.pmzdbt

        binding.rvContacts.adapter = contactsAdapter

        binding.ivTopBg.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                (binding.tvTitle.layoutParams as ConstraintLayout.LayoutParams).topMargin = (binding.ivTopBg.height * 94f / 250f).toInt()
                (binding.layoutContent.layoutParams as ConstraintLayout.LayoutParams).topMargin = (binding.ivTopBg.height * 178f / 250f).toInt()

                binding.layoutContent.setupWith(binding.nestedScrollView).setFrameClearDrawable(binding.layoutContent.background).setBlurRadius(5f)
                binding.ivTopBg.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

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

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

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()
        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, "")
        }

        binding.ivImage.onClick {
            if (image != null) {
                PublicActivity.start(requireContext(), PhotoViewFragment::class.java, Pair("photos", listOf(image!!.url)))
            }
        }
        binding.ivAddImage.onClick {
            if (image == null) {
                PermissionUtils.checkPhotoPermission(requireActivity(), childFragmentManager) { isGranted ->
                    if (isGranted) {
                        imageLauncher.launch("image/*")
                    }
                }
            }
        }
        binding.ivDeleteImage.onClick {
            if (companyDetail == null && image != null) {
                mViewModel.deleteImage(image!!.id)
            }
            image = null
            binding.ivImage.load("")
            binding.ivAddImage.visible()
            binding.ivDeleteImage.gone()
        }

        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.btnNext.onClick {
            val name = binding.etName.text.toString().trim()
            if (TextUtils.isEmpty(name)) {
                toast("请输入企业名称")
                return@onClick
            }
            if (city == null) {
                toast("请选择地区")
                return@onClick
            }
            if (image == null) {
                toast("请上传营业执照")
                return@onClick
            }
            if (contactsAdapter.data.isEmpty()) {
                toast("请添加联系人")
                return@onClick
            }
            if (UserConfigManager.userInfo?.vip != "1") {
                commit()
            } else {
                PublicActivity.start(requireContext(), VipFragment::class.java, Pair("origin", "enterprise_auth"))
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.userInfoLiveData.observe(this) {
            UserConfigManager.userInfoLiveData.postValue(it)
        }

        mViewModel.addLiveData.observe(this) {
            toast("提交成功")
            requireActivity().finish()
        }

        mViewModel.companyLiveData.observe(this) {
            companyDetail = it
            if (companyDetail != null) {
                setData(companyDetail!!)
            }
        }

        mViewModel.imageLiveData.observe(this) {
            image = it
            binding.ivImage.load(it.url) {
                transformations(RoundedCornersTransformation(DensityUtils.dp2px(8f).toFloat()))
            }
            binding.ivAddImage.gone()
            binding.ivDeleteImage.visible()
        }
    }

    private fun commit() {
        val name = binding.etName.text.toString().trim()
        val jsonObject = JsonObject()
        jsonObject.addProperty("company_name", name)
        jsonObject.addProperty("city_id", "${city!!.id}")
        jsonObject.addProperty("file_id", image!!.id)

        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 (companyDetail == null) {
            mViewModel.addCompanyInfo(jsonObject.toString().toRequestBody())
        } else {
            jsonObject.addProperty("id", companyDetail!!.id)
            mViewModel.updateCompanyInfo(jsonObject.toString().toRequestBody())
        }
        RxBus.defaultInstance.post(CompanyAuthEvent())
    }

    @SuppressLint("SetTextI18n")
    private fun setData(detail: CompanyEntity) {
        when (detail.status) {
            "1" -> {
                binding.etName.isEnabled = false
                binding.tvArea.isEnabled = false
                binding.ivAddImage.isEnabled = false
                binding.ivDeleteImage.isEnabled = false
                binding.rvContacts.isEnabled = false
                binding.ivAddContacts.isEnabled = false
                binding.btnNext.isEnabled = false
                binding.layoutRejectReason.gone()

                binding.btnNext.text = "审核中"
            }
            "2" -> {
                binding.tvStatus.text = "认证成功"
                binding.tvStatus.setTextColor(getColor(R.color.color_3bbf0f))
                binding.tvStatus.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_auth_success, 0, 0, 0)
                binding.tvReason.gone()
                binding.layoutRejectReason.setLayoutBackground(getColor(R.color.color_e3fae7))
                binding.layoutRejectReason.visible()

                binding.btnNext.text = "重新提交"
            }
            "3" -> {
                binding.tvStatus.text = "认证失败"
                binding.tvStatus.setTextColor(getColor(R.color.color_ff592b))
                binding.tvStatus.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_auth_fail, 0, 0, 0)
                binding.tvReason.text = "理由：${detail.remark}"
                binding.layoutRejectReason.setLayoutBackground(getColor(R.color.color_fff5f3))
                binding.layoutRejectReason.visible()

                binding.btnNext.text = "重新提交"
            }
            else -> {
                binding.layoutRejectReason.gone()
            }
        }
        binding.etName.setText(detail.company_name)

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

        image = UploadFileEntity(detail.file_id, detail.file_url)
        binding.ivImage.load(image!!.url) {
            transformations(RoundedCornersTransformation(DensityUtils.dp2px(8f).toFloat()))
        }
        binding.ivAddImage.gone()
        binding.ivDeleteImage.visible()

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