package com.cheng.blzb.ui.fragment.mine.order.cert

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.activity.result.contract.ActivityResultContracts
import coil.load
import coil.transform.RoundedCornersTransformation
import com.cheng.blzb.bean.OrderEntity
import com.cheng.blzb.databinding.FragmentCertificateBinding
import com.cheng.blzb.event.OrderEvent
import com.cheng.blzb.ui.activity.MainActivity
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.mine.order.OrderFragment
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.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.startActivity
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.ClipboardUtils
import com.example.base.utils.DensityUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import okhttp3.RequestBody.Companion.toRequestBody
import org.jetbrains.anko.startActivity
import java.text.DecimalFormat

class CertificateFragment: BaseFragment<FragmentCertificateBinding, CertificateViewModel>() {
    private val from by lazy { arguments?.getInt("from") ?: 0 }
    private val orderId by lazy { arguments?.getString("orderId") ?: "" }

    private var orderInfo: OrderEntity? = null
    private var transInfo: OrderEntity.TransInfo? = null

    private var imagePath: String? = null

    private val imageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.let {
            imagePath = FileProviderUtils.getFileAbsolutePath(requireContext(), it)
            if (!TextUtils.isEmpty(imagePath)) {
                binding.ivImage.load(imagePath) {
                    transformations(RoundedCornersTransformation(DensityUtils.dp2px(8f).toFloat()))
                }
                binding.ivAddImage.gone()
                binding.ivDeleteImage.visible()
            }
        }
    }

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

    override fun initData() {
        super.initData()
        mViewModel.getOrderInfo(orderId)
    }

    override fun initListener() {
        super.initListener()
        binding.btnCopy.onClick {
            ClipboardUtils.copyText(orderInfo!!.pay_params)
            toast("复制成功")
        }

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

        binding.btnNext.onClick {
            if (TextUtils.isEmpty(imagePath)) {
                toast("请上传凭证")
                return@onClick
            }
            mViewModel.uploadImg(requireContext(), imagePath!!)
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.orderLiveData.observe(this) {
            orderInfo = it
            if (!TextUtils.isEmpty(it.pay_params)) {
                transInfo = Gson().fromJson(it.pay_params, OrderEntity.TransInfo::class.java)
                setTransInfo()
            }
        }

        mViewModel.imageLiveData.observe(this) {
            val jsonObject = JsonObject()
            jsonObject.addProperty("order_id", orderId)
            jsonObject.addProperty("bank_bill_url", it.url)
            mViewModel.updateOrder(jsonObject.toString().toRequestBody())
        }

        mViewModel.updateLiveData.observe(this) {
            toast("提交成功")
            RxBus.defaultInstance.post(OrderEvent())
            if (from == 1) {
                PublicActivity.start(requireContext(), OrderFragment::class.java, Pair("from", 1))
            }
            requireActivity().finish()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setTransInfo() {
        if (transInfo != null) {
            binding.tvAccountName.text = transInfo!!.accountName
            binding.tvAccountNo.text = transInfo!!.accountNo
            binding.tvBankName.text = transInfo!!.bankName
            binding.tvBankNo.text = transInfo!!.bankNo
            binding.tvCode.text = orderInfo!!.id
            binding.tvAmount.text = "￥${DecimalFormat("0.00").format(orderInfo!!.total_fee.toFloat())}"
        }
    }
}