package com.gingersoft.gsa.other_order_mode.ui.activity

import android.animation.ValueAnimator
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.other_order_mode.R
import com.gingersoft.gsa.other_order_mode.databinding.ActivityOtherOrderBinding
import com.gingersoft.gsa.other_order_mode.model.viewModel.PageViewModel
import com.gingersoft.gsa.other_order_mode.service.GetInfoUpdateService
import com.gingersoft.gsa.other_order_mode.ui.adapter.SectionsPagerAdapter
import com.gingersoft.gsa.other_order_mode.ui.base.BaseActivity
import com.gingersoft.gsa.other_order_mode.util.InjectorUtil
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopups
import kotlinx.android.synthetic.main.activity_other_order.*


class OtherOrderActivity : BaseActivity() {

    private val pageViewModel by lazy { ViewModelProvider(this, InjectorUtil.getWeatherModelFactory())[PageViewModel::class.java] }
    private val instance by lazy { this }

    private val ints = arrayOf(
            R.string.tab_text_1,
            R.string.tab_text_2,
            R.string.tab_text_3,
            R.string.tab_text_4,
            R.string.tab_text_5
    )

    private val colors = arrayOf(
            R.color.other_order_num_color_first,
            R.color.other_order_num_color_second,
            R.color.other_order_num_color_third,
            R.color.other_order_num_color_fourth,
            R.color.other_order_num_color_fifth
    )

    private var titles: ArrayList<TextView> = ArrayList()
    private var layoutHeight: Float = 0F
    private var btnHeight: Float = 0F
    private var selectPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityOtherOrderBinding = DataBindingUtil.setContentView(this, R.layout.activity_other_order)

        initWebsocket()
        initAppTop()
        initSwitchRestStatus()

        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager, ints)
        view_pager.adapter = sectionsPagerAdapter
        view_pager.offscreenPageLimit = 4
        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                selectPosition = position
            }
        })

        searchMethod(view_pager)
        initTabs()
        //餐廳營業信息
        loadRestaurantInfo(binding)

        cl_order_info.post {
            layoutHeight = cl_order_info.height.toFloat()
        }
        btn_open_or_close_info.post {
            btnHeight = btn_open_or_close_info.height.toFloat()
        }
        pageViewModel.getDeliveryInfo(this)
    }

    /**
     * 加載餐廳營業信息
     */
    private fun loadRestaurantInfo(binding: ActivityOtherOrderBinding) {
        pageViewModel.otherInfo.observe(this, Observer {
            binding.data = pageViewModel
            sb_takeaway.max = if (it.MaxOrder == 0) 1 else it.MaxOrder
            sb_takeaway.progress = it.num

            sb_self.max = it.maxOrderSelf
            sb_self.progress = it.selflNum

            if (it.orderType_2 != null) {
                tv_takeaway_num.text = it.orderType_2!!.typeDayOrderNum.toString()
                tv_takeaway_amount.text = "$" + it.orderType_2!!.typeTotalAmount.toString()
            }
            if (it.orderType_7 != null) {
                tv_today_self_order_num.text = it.orderType_7!!.typeDayOrderNum.toString()
                tv_today_self_amount_num.text = "$" + it.orderType_7!!.typeTotalAmount.toString()
            }
        })
    }

    /**
     * 初始化viewpager的tab指示器
     */
    private fun initTabs() {
        tabs.setupWithViewPager(view_pager)

        for (i in 0 until ints.size) {
            //获取每一个tab对象
            val tabAt = tabs.getTabAt(i)
            if (tabAt != null) {
                //将每一个条目设置我们自定义的视图
                tabAt.setCustomView(R.layout.layout_table_count_item)
                //通过tab对象找到自定义视图的ID
                val mTvTitle = tabAt.customView!!.findViewById<TextView>(R.id.tv_table_item_title)
                val mNumber = tabAt.customView!!.findViewById<TextView>(R.id.tv_table_item_num)
                titles.add(mNumber)
                mTvTitle.setText(ints[i])

                mNumber.text = "0"
                mNumber.setTextColor(this@OtherOrderActivity.resources.getColor(colors[i]))
                while (pageViewModel.mOrderNum.size <= i) {
                    pageViewModel.mOrderNum.add(MutableLiveData())
                }
                pageViewModel.mOrderNum[i].observe(instance, Observer {
                    mNumber.text = it.toString()
                })
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchMethod(viewPager: ViewPager) {
        iv_search_order.setOnClickListener {
            //搜索
            if (ed_order_num_search.text != null && ed_order_num_search.text.isNotEmpty()) {
                pageViewModel.phone = ed_order_num_search.text.toString()
                pageViewModel.getOrderList(this, viewPager.currentItem, "0", false) {
                    ToastUtils.show(this@OtherOrderActivity, "搜索到$it" + "條數據")
                }
            } else {
                ToastUtils.show(this@OtherOrderActivity, "請輸入手機號或訂單號")
            }
        }
    }

    private var restaurantPopup: QMUIPopup? = null
    private var stateBg = GradientDrawable()
    /**
     * 切換餐廳狀態按鈕
     */
    private fun initSwitchRestStatus() {
        stateBg.cornerRadius = QMUIDisplayHelper.dp2px(this, 4).toFloat()

        //切換營業狀態
        tv_restaurant_state.setOnClickListener {
            if (restaurantPopup == null) {
                val view: View = LayoutInflater.from(this).inflate(R.layout.popup_layout_restaurant_state, null)
                restaurantPopup = QMUIPopups.popup(this)
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(view)
                        .radius(QMUIDisplayHelper.dp2px(this, 5))
                        .arrow(false)
                        .shadow(false)
                        .offsetYIfTop(0)
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .show(it)
                view.apply {
                    //營業中
                    findViewById<TextView>(R.id.tv_restaurant_open).setOnClickListener {
                        updateRestaurantState(1)
                    }
                    //休息中
                    findViewById<TextView>(R.id.tv_restaurant_close).setOnClickListener {
                        updateRestaurantState(0)
                    }
                    //繁忙不接單
                    findViewById<TextView>(R.id.tv_restaurant_busy_close).setOnClickListener {
                        updateRestaurantState(2)
                    }
                    //繁忙可接單
                    findViewById<TextView>(R.id.tv_restaurant_busy_open).setOnClickListener {
                        updateRestaurantState(3)
                    }
                }
            } else {
                restaurantPopup?.show(it)
            }
        }

        //綁定營業按鈕狀態
        pageViewModel.restaurantState.observe(this, Observer {
            when (it) {
                0 -> {
                    tv_restaurant_state.text = "休息中"
                    stateBg.setColor(ContextCompat.getColor(this, R.color.color_c8))
                }
                1 -> {
                    tv_restaurant_state.text = "營業中"
                    stateBg.setColor(ContextCompat.getColor(this, R.color.restaurant_color_open))
                }
                2 -> {
                    tv_restaurant_state.text = "繁忙不接"
                    stateBg.setColor(ContextCompat.getColor(this, R.color.restaurant_color_busy_close))
                }
                3 -> {
                    tv_restaurant_state.text = "繁忙可接"
                    stateBg.setColor(ContextCompat.getColor(this, R.color.restaurant_color_busy_open))
                }
            }
            tv_restaurant_state.background = stateBg
        })
        btn_open_or_close_info.setOnClickListener {
            setOrderInfoOpenOrClose()
        }
    }

    private fun updateRestaurantState(state: Int) {
        pageViewModel.setRestaurantState(this@OtherOrderActivity, state)
        restaurantPopup?.dismiss()
    }

    private fun initWebsocket() {
        //開啟websocket
        val intent = Intent(this, GetInfoUpdateService::class.java)
        startService(intent)
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
    }

    private var serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val bind: GetInfoUpdateService.MyBind = service as GetInfoUpdateService.MyBind
            bind.setOnPostCallBack(object : GetInfoUpdateService.PostCallBack {
                override fun callBack(type: Int) {
                    //-1斷開連接,\n-2:消息傳輸錯誤,\n0:連接消息,\n1：登錄通知,\n2：登出通知,\n3：外賣送單通知,\n4：自取送單通知,\n5:歷史訂單通知,\n6:修改訂單狀態通知,\n7:支付成功通知"
                    Log.e("message", "消息類型$type")
                    if (type == 3 || type == 4 || type == 5
                            || type == 6 || type == 7) {
//                        if (type == 6 || type == 7) {
//
//                        } else {
//                            //播放提示音
//                            initSoundPool()
//                        }
                        pageViewModel.refreshState.postValue(selectPosition)
                    }
                }
            })
        }

        override fun onServiceDisconnected(name: ComponentName) {

        }
    }

//    private var soundPool: SoundPool? = null
//    fun initSoundPool() {
//        //实例化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。
//        val voiceId = soundPool!!.load(this, R.raw.newordervocal, 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)
//            }
//        }
//    }

    private var isOpen: Boolean = true
    private val btnOpenBg by lazy { ContextCompat.getDrawable(this, R.drawable.shape_white_bottom_border)!! }
    private val btnCloseBg by lazy { ContextCompat.getDrawable(this, R.drawable.shape_dialog_bg)!! }
    /**
     * 顯示或收起餐廳營業信息
     */
    private fun setOrderInfoOpenOrClose() {
        btn_open_or_close_info.isClickable = false
        isOpen = !isOpen
        //如果是打開的，則關閉
        val heightAnimation = if (isOpen)
            ValueAnimator.ofFloat(btnHeight, layoutHeight)
        else
            ValueAnimator.ofFloat(layoutHeight, btnHeight)
        heightAnimation.duration = 200
        heightAnimation.addUpdateListener { animation ->
            val height = animation.animatedValue as Float

            setViewHeight(cl_order_info, height.toInt())

            if (height >= layoutHeight * 0.8) {
                btn_open_or_close_info.apply {
                    if (isOpen) {
                        text = "點擊收起"
                        background = btnOpenBg
                        layout_search_info.visibility = View.VISIBLE
                        layout_today_order_info.visibility = View.VISIBLE
                    } else {
                        text = "查看詳情"
                        background = btnCloseBg
                        layout_search_info.visibility = View.GONE
                        layout_today_order_info.visibility = View.GONE
                    }
                }
                btn_open_or_close_info.isClickable = true
            }
        }
        heightAnimation.start()
    }

    private fun setViewHeight(view: View, height: Int) {
        val params = view.layoutParams
        params.height = height
        view.requestLayout()
    }

    private var pop: QMUIPopup? = null
    /**
     * 初始化標題欄
     */
    private fun initAppTop() {
        qm_other_order_bar.setTitle(GsaCloudApplication.getRestaurantName(this))
        qm_other_order_bar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener { finish() }
        qm_other_order_bar.addRightImageButton(R.drawable.icon_topbar_overflow, R.id.topbar_right_change_button).setOnClickListener {
            //彈出彈窗
            if (pop == null) {
                val view = LayoutInflater.from(this).inflate(R.layout.layout_more_popup, null)

                pop = QMUIPopups.popup(this)
                        .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                        .view(view)
                        .radius(QMUIDisplayHelper.dp2px(this, 5))
                        .arrow(true)
                        .shadow(true)
                        .dimAmount(0.6f)
                        .offsetYIfTop(0)
                        .animStyle(QMUIPopup.ANIM_AUTO)
                        .show(it)

                view.findViewById<QMUIAlphaTextView>(R.id.tv_delivery_setting).setOnClickListener {
                    //備送設置
                    startActivity(Intent(this, DeliverySettingActivity::class.java))
                    pop!!.dismiss()
                }
                view.findViewById<QMUIAlphaTextView>(R.id.tv_history_order).setOnClickListener {
                    //歷史訂單
                    startActivity(Intent(this, HistoryOrderActivity::class.java))
                    pop!!.dismiss()
                }
                view.findViewById<QMUIAlphaTextView>(R.id.tv_open_cash_box).setOnClickListener {
                    //開錢箱
                    pageViewModel.openCashBox()
                    pop!!.dismiss()
                }
            } else {
                pop!!.show(it)
            }
        }
//        qm_other_order_bar.addRightImageButton(R.drawable.ic_history_order, R.id.iv_history).setOnClickListener {
//            //歷史訂單
//            startActivity(Intent(this, HistoryOrderActivity::class.java))
//        }
        qm_other_order_bar.setBackgroundColor(resources.getColor(R.color.theme_color))
    }
}