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.text.TextUtils
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.app.GsaCloudApplication
import com.gingersoft.gsa.cloud.common.core.delivery.OrderDetails
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil
import com.gingersoft.gsa.cloud.pay.contract.PayTypeContract
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils
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.HistoryOrderAdapter
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,orderPayType :Int, payType: Int, refundStatus: Int, reasonDesc: String = "", 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 ivOrderState = hepler.getView<ImageView>(R.id.iv_order_state)
                    var tv_receive_address_text = hepler.getView<TextView>(R.id.tv_receive_address_text)
                    var tv_receive_address = hepler.getView<TextView>(R.id.tv_receive_address)
                    var tv_cancel_reason_text = hepler.getView<TextView>(R.id.tv_cancel_reason_text)
                    var tv_cancel_reason = hepler.getView<TextView>(R.id.tv_cancel_reason)
                    var tv_refund_reason_text = hepler.getView<TextView>(R.id.tv_refund_reason_text)
                    var tv_refund_reason = hepler.getView<TextView>(R.id.tv_refund_reason)
                    val orderData = data.data!![0]
                    val layoutOrderInfoDialogBinding: LayoutOrderInfoDialogNewBinding = DataBindingUtil.bind(hepler.contentView)!!
                    var totalAmount = orderData.TOTAL_AMOUNT!!.toDouble()
                    orderData.couponList?.let {
                        for (coupon in it) {
                            totalAmount = MoneyUtil.sub(totalAmount, coupon.discount_amount)
                        }
                    }
                    layoutOrderInfoDialogBinding.data = orderData
                    layoutOrderInfoDialogBinding.isSelf = orderType == 7
                    layoutOrderInfoDialogBinding.totalAmount = totalAmount
                    //是歷史訂單，就不顯示訂單狀態
                    layoutOrderInfoDialogBinding.isHistory = isHistory
                    var btnContent: String
                    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 = "取消訂單"
                        }
                    }
                    when (orderStuats) {
                        4 -> {
                            //已完成訂單
                            ivOrderState.setImageResource(R.drawable.ic_has_end)
                            tv_cancel_reason_text.visibility = View.GONE
                            tv_cancel_reason.visibility = View.GONE
                            tv_refund_reason_text.visibility = View.GONE
                            tv_refund_reason.visibility = View.GONE
                            tv_receive_address_text.visibility = View.GONE
                            tv_receive_address.visibility = View.GONE
                        }
                        6 -> {
                            //已取消訂單
                            ivOrderState.setImageResource(R.drawable.img_cancelled)
                            setOrderReason(hepler, orderStuats, refundStatus, orderPayType,payType, reasonDesc)
                        }
                    }
//                    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("支付金額:", totalAmount, 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 fun setOrderReason(holder: DialogUtils.ViewHepler, orderStatus: Int, refundStatus: Int, orderPayType: Int,payType: Int,  reasonDesc: String) {
        var tv_address_text = holder.getView<TextView>(R.id.tv_receive_address_text)
        var tv_address = holder.getView<TextView>(R.id.tv_receive_address)
        var tv_cancel_reason_text = holder.getView<TextView>(R.id.tv_cancel_reason_text)
        var tv_cancel_reason = holder.getView<TextView>(R.id.tv_cancel_reason)
        var tv_refund_reason_text = holder.getView<TextView>(R.id.tv_refund_reason_text)
        var tv_refund_reason = holder.getView<TextView>(R.id.tv_refund_reason)
        var refundReason = getRefundReasonByStatus(refundStatus, orderPayType,payType);
        if (!TextUtils.isEmpty(refundReason)) {
            if (refundStatus == 5) {
                tv_refund_reason.setTextColor(getColor(R.color.green_400))
            } else {
                tv_refund_reason.setTextColor(getColor(R.color.red))
            }
            tv_refund_reason.setText(refundReason)
            tv_refund_reason_text.setText("退款進度：")
            tv_refund_reason_text.visibility = View.VISIBLE
            tv_refund_reason.visibility = View.VISIBLE

            tv_address_text.visibility = View.GONE
            tv_address.visibility = View.GONE
        } else {
            tv_refund_reason_text.visibility = View.GONE
            tv_refund_reason.visibility = View.GONE

            tv_address_text.visibility = View.VISIBLE
            tv_address.visibility = View.VISIBLE
        }
        if (reasonDesc != null) {
            tv_cancel_reason.setText(reasonDesc)
            tv_cancel_reason_text.setText("取消原因：")
            tv_cancel_reason_text.visibility = View.VISIBLE
            tv_cancel_reason.visibility = View.VISIBLE
        } else {
            tv_cancel_reason_text.visibility = View.GONE
            tv_cancel_reason.visibility = View.GONE
        }
    }

    /**
     * 獲取退款說明
     */
    private fun getRefundReasonByStatus(refundStatus: Int, orderPayType: Int,payType: Int): String {
        when (refundStatus) {
            5 -> {
                return "退款完成"
            }
            else -> {
                when (orderPayType) {
                    1 -> {
                        return "無"
                    }
                    else -> {
                        when (payType) {
                            PayTypeContract.PAY_METHOD_ID_1021 -> { //Google pay需要5-7天
                                return "退款中(預計5-7個工作日退回原賬戶)"
                            }
                            else -> {
                                return "退款中(預計1-3個工作日退回原賬戶)"
                            }
                        }
                    }
                }
            }
        }
        return "";
    }

    private fun getColor(color: Int): Int {
        return ContextCompat.getColor(GsaCloudApplication.getAppContext(), color)
    }

    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, _, 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)
            }
        }
    }

}