package com.quyunshuo.module.home.fragment.fragment.pay

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.View
import androidx.fragment.app.viewModels
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.ShoppingCartBean
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.databinding.HomeFragmentQrCodeBinding
import com.quyunshuo.module.home.fragment.vm.QrCodeFragmentVM
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus

/**
 * 首页Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@AndroidEntryPoint
class QrCodeFragment : BaseFragment<HomeFragmentQrCodeBinding, QrCodeFragmentVM>()  {

    override val mViewModel: QrCodeFragmentVM by viewModels()
    override fun createVB() = HomeFragmentQrCodeBinding.inflate(layoutInflater)

    private var selectPro:String?= null//传递过来的购物车内容
    private var promotionCode:String?=null//传递过来的优惠码

    override fun HomeFragmentQrCodeBinding.initView() {
        with(ivReset){
            setOnClickListener {
                mViewModel.twoPayCode(selectPro)
                visibility = View.GONE
                pbQrLoading.visibility =View.VISIBLE

            }
        }
    }

    override fun initObserve() {
        observeLiveData(mViewModel.qrCode,::showQrCode)
    }

    private fun showQrCode(qrCode: String) {
        mBinding.pbQrLoading.visibility = View.GONE
        if (qrCode=="") {
            mBinding.ivReset.visibility = View.VISIBLE
            ToastUtil.switchToastStyleToWarn("网络不好，请重试")
            return
        }
        if (isBase64Img(qrCode)) {
            val bitmap: Bitmap = stringToBitmap(qrCode)
            mBinding.ivQrCode.setImageBitmap(bitmap)
        }else if("0"==qrCode) {
            // 优惠码支付成功
            EventBus.getDefault().post(ApiMessageEvent(MqName.PAY_SUCCESS, ""))
            return
        }else{
            mBinding.ivReset.visibility = View.VISIBLE
            ToastUtil.switchToastStyleToWarn(qrCode)
            return
        }

    }

    override fun initRequestData() {
        selectPro = arguments?.getString("SELECT_PRO")
        promotionCode = arguments?.getString("PROMOTION_CODE")
        Log.d("backinfo","选择的商品："+selectPro)
        //是否为购物车模式  不管是否为购物车模式，都使用twoPayCodeShoppingCart  因为单选其实就是限制购物车只能一个。
//        val isShoppingTrolley = SpUtils.getBoolean(MMKVName.SHOPPING_TROLLEY, true)
//        if (isShoppingTrolley!!){
            val arrayList: ArrayList<ShoppingCartBean> = Gson().fromJson(
                selectPro,
                object : TypeToken<ArrayList<ShoppingCartBean?>?>() {}.type
            )
            mViewModel.twoPayCodeShoppingCart(arrayList,promotionCode)
//        }else{
            //
//            mViewModel.twoPayCode(selectPro,promotionCode)
//        }

    }

    fun isBase64Img(imgurl: String): Boolean {
        if (!TextUtils.isEmpty(imgurl) &&
            (imgurl.startsWith("data:image/png;base64,")
                    || imgurl.startsWith("data:image/*;base64,")
                    || imgurl.startsWith("data:image/jpg;base64,"))
        ) {
            return true
        }
        return false
    }

    /**
     * base64转换成图片
     *
     * @param string
     * @return
     */
    fun stringToBitmap(string: String): Bitmap {
        var bitmap: Bitmap? = null
        try {
            val bitmapArray =
                Base64.decode(string.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()[1], Base64.DEFAULT)
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.size)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return bitmap!!
    }
}