package com.gingersoft.gsa.delivery_pick_mode.util

import android.app.Dialog
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil
import com.gingersoft.gsa.cloud.common.ui.widget.dialog.DialogUtils
import com.gingersoft.gsa.cloud.common.core.print.bean.OrderDetails
import com.gingersoft.gsa.delivery_pick_mode.R
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.BillBean
import com.gingersoft.gsa.delivery_pick_mode.databinding.LayoutOrderInfoDialogNewBinding
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.FoodListAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.PayBillAdapter
import com.jess.arms.utils.ArmsUtils
import java.lang.Double.parseDouble

object OtherOrderUtils {

    fun showOrderDetailsDialog(context: Context, data: OrderDetails, orderStuats: Int, orderType: Int, isHistory: Boolean = false, listenter: ((view: View, data: OrderDetails.DataBean, dialog: Dialog) -> Unit)?) {
        object : DialogUtils(context, R.layout.layout_order_info_dialog_new) {
            override fun initLayout(hepler: ViewHepler, dialog: Dialog) {
                if (data.data != null) {
                    val tvStatus = hepler.getView<TextView>(R.id.tv_order_state)
                    val orderData = data.data!![0]
                    val layoutOrderInfoDialogBinding: LayoutOrderInfoDialogNewBinding = DataBindingUtil.bind(hepler.contentView)!!
                    val totalAmount = orderData.TOTAL_AMOUNT!!.toDouble()

                    layoutOrderInfoDialogBinding.data = orderData
                    layoutOrderInfoDialogBinding.isSelf = orderType == 7
                    layoutOrderInfoDialogBinding.totalAmount = totalAmount
                    //是歷史訂單，就不顯示訂單狀態
                    layoutOrderInfoDialogBinding.isHistory = isHistory
                    var btnContent = ""
                    var cancelBtnContent = ""

                    val type = if (orderType == 7) "自取" else "外送"
                    val orderStatus: String

                    when (orderStuats) {
                        2 -> {
                            if (orderType == 7) {
                                //自取
                                btnContent = "製作完成"
                                tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_state0_color))
                                cancelBtnContent = "取消訂單"
                            } else {
                                if (orderData.isDelete == 0) {
                                    btnContent = "重印"
                                    cancelBtnContent = "取消物流"
                                } else {
                                    btnContent = "指派送貨"
                                    cancelBtnContent = "取消訂單"
                                }
                                tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_state1_color))
                            }
                            orderStatus = "製作中"
                        }
                        3 -> {
                            btnContent = "結賬"
                            if (orderType == 7) {
                                //自取
                                orderStatus = "待取餐"
                                tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_state3_color))
                            } else {
                                if (orderData.isDelete == 0) {
                                    //如果是第三方物流，不顯示結賬按鈕
                                    btnContent = "重印"
                                }
                                orderStatus = "派送中"
                                tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_state2_color))
                            }
                        }
                        else -> {
                            btnContent = "確認訂單"
                            orderStatus = "待確認"
                            tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_state0_color))
                            cancelBtnContent = "取消訂單"
                        }
                    }
//                    val payName = StringBuffer()
//                    if (orderData.payMultiple != null) {
//                        for (payMethod in orderData.payMultiple!!) {
//                            if (!TextUtil.isEmptyOrNullOrUndefined(payMethod.payName)) {
//                                payName.append(payMethod.payName)
//                                payName.append(",")
//                            }
//                        }
//                        if (payName.isNotEmpty()) {
//                            payName.deleteCharAt(payName.length - 1)
//                        }
//                        layoutOrderInfoDialogBinding.payMethod = payName.toString()
//                    } else {
//                        layoutOrderInfoDialogBinding.payMethod = when (orderData.payType) {
//                            1 -> "積分支付"
//                            2 -> "支付寶"
//                            3 -> "财付通"
//                            4 -> "微信支付"
//                            5 -> "貨到付款"
//                            6 -> "其他支付"
//                            else -> ""
//                        }
//                    }

                    val billBeans = ArrayList<BillBean>()
                    billBeans.add(BillBean("合計:", MoneyUtil.sub(MoneyUtil.sub(totalAmount, orderData.Lunchbox), orderData.DELIVERY_CHARGE), 0))
                    if (orderData.Lunchbox != 0.0) {
                        billBeans.add(BillBean("餐盒費:", orderData.Lunchbox, 0))
                    }
                    if (orderData.DELIVERY_CHARGE != 0.0) {
                        billBeans.add(BillBean("送貨費:", orderData.DELIVERY_CHARGE, 0))
                    }
//                    if (orderData.discount_amount != 0.0) {
//                        billBeans.add(BillBean("折扣:", orderData.discount_amount, 0))
//                    }
//                    billBeans.add(BillBean("支付金額:", MoneyUtil.sub(totalAmount, orderData.discount_amount), 1))
                    orderData.couponList?.let {
                        for (coupon in it) {
                            if (TextUtil.isNotEmptyOrNullOrUndefined(coupon.couponName)) {
                                billBeans.add(BillBean(coupon.couponName, parseDouble(coupon.discount_amount.toString()), 1))
                            }
                        }
                    }
                    billBeans.add(BillBean("支付金額:", MoneyUtil.sub(totalAmount, orderData.discount_amount), 1))

                    orderData.payMultiple?.let {
                        for (payMultiple in it) {
                            if (TextUtil.isNotEmptyOrNullOrUndefined(payMultiple.payName)) {
                                billBeans.add(BillBean(payMultiple.payName + ":", payMultiple.amount, 1))
                            }
                        }
                    }
                    val rvBillInfo = hepler.getView<RecyclerView>(R.id.recycler_order_details_pay_info)
                    rvBillInfo.layoutManager = LinearLayoutManager(context)
                    rvBillInfo.adapter = PayBillAdapter(R.layout.item_orderdetails_bill_info, billBeans)

                    if (isHistory) {
                        cancelBtnContent = ""
                        btnContent = "重印"
                    }
                    layoutOrderInfoDialogBinding.orderStatus = type + orderStatus
                    layoutOrderInfoDialogBinding.btnContent = btnContent
                    layoutOrderInfoDialogBinding.cancelBtnContent = cancelBtnContent
                    layoutOrderInfoDialogBinding.estimatedTime = orderData.estimatedTime
                }

                val rvFood: RecyclerView = hepler.getView(R.id.rv_food)
                rvFood.layoutManager = LinearLayoutManager(context)
                rvFood.adapter = FoodListAdapter(context, data.data!![0].PRODUCT_NAME!!)
                hepler.setOnClickListenter(R.id.btn_assign_shipping) {
                    //指派送貨或是確認訂單？
                    //確認訂單，調用接口，並打印
                    listenter?.invoke(it, data.data!![0], dialog)
                }

                hepler.setOnClickListenter(R.id.btn_cancel_order) {
                    //取消訂單
                    listenter?.invoke(it, data.data!![0], dialog)
                }

                hepler.getView<ImageView>(R.id.iv_close).setOnClickListener {
                    dialog.dismiss()
                }
            }
        }.setWidth((ArmsUtils.getScreenWidth(context) * 0.9).toInt())
                .setHeight((ArmsUtils.getScreenHeidth(context) * 0.9).toInt())
                .show()

    }

    private var soundPool: SoundPool? = null

    fun initSoundPool(context: Context, resId: Int) {
        //实例化SoundPool
        //sdk版本21是SoundPool 的一个分水岭
        if (soundPool == null) {
            if (Build.VERSION.SDK_INT >= 21) {
                val builder = SoundPool.Builder()
                //传入最多播放音频数量,
                builder.setMaxStreams(1)
                //AudioAttributes是一个封装音频各种属性的方法
                val attrBuilder = AudioAttributes.Builder()
                //设置音频流的合适的属性
                attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC)
                //加载一个AudioAttributes
                builder.setAudioAttributes(attrBuilder.build())
                soundPool = builder.build()
            } else {
                /**
                 * 第一个参数：int maxStreams：SoundPool对象的最大并发流数
                 * 第二个参数：int streamType：AudioManager中描述的音频流类型
                 *第三个参数：int srcQuality：采样率转换器的质量。 目前没有效果。 使用0作为默认值。
                 */
                soundPool = SoundPool(1, AudioManager.STREAM_MUSIC, 0)
            }
        }
        //可以通过四种途径来记载一个音频资源：
        //1.通过一个AssetFileDescriptor对象
        //int load(AssetFileDescriptor afd, int priority)
        //2.通过一个资源ID
        //int load(Context context, int resId, int priority)
        //3.通过指定的路径加载
        //int load(String path, int priority)
        //4.通过FileDescriptor加载
        //int load(FileDescriptor fd, long offset, long length, int priority)
        //声音ID 加载音频资源,这里用的是第二种，第三个参数为priority，声音的优先级*API中指出，priority参数目前没有效果，建议设置为1。
        loadSound(context, resId)
    }

    private fun loadSound(context: Context, resId: Int) {
        val voiceId = soundPool!!.load(context, resId, 1)
        //异步需要等待加载完成，音频才能播放成功
        soundPool!!.setOnLoadCompleteListener { soundPool, sampleId, status ->
            if (status == 0) {
                //第一个参数soundID
                //第二个参数leftVolume为左侧音量值（范围= 0.0到1.0）
                //第三个参数rightVolume为右的音量值（范围= 0.0到1.0）
                //第四个参数priority 为流的优先级，值越大优先级高，影响当同时播放数量超出了最大支持数时SoundPool对该流的处理
                //第五个参数loop 为音频重复播放次数，0为值播放一次，-1为无限循环，其他值为播放loop+1次
                //第六个参数 rate为播放的速率，范围0.5-2.0(0.5为一半速率，1.0为正常速率，2.0为两倍速率)
                soundPool.play(voiceId, 1f, 1f, 1, 0, 1f)
            }
        }
    }

}