package com.gingersoft.gsa.delivery_pick_mode.ui.activity

import android.animation.ValueAnimator
import android.app.Dialog
import android.content.*
import android.graphics.drawable.GradientDrawable
import android.net.Uri
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.app.NotificationManagerCompat
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.billy.cc.core.component.CC
import com.gingersoft.gsa.cloud.common.constans.AppConstans
import com.gingersoft.gsa.cloud.common.constans.ExpandConstant
import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans.TAKEAWAY_TYPE
import com.gingersoft.gsa.cloud.common.constans.FunctionManagerConstants
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils
import com.gingersoft.gsa.cloud.common.function.FunctionManager
import com.gingersoft.gsa.cloud.common.service.DataNotificationService
import com.gingersoft.gsa.cloud.common.service.PostCallBack
import com.gingersoft.gsa.cloud.common.utils.other.SPUtils
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.order.order.BaseOrder
import com.gingersoft.gsa.cloud.ui.utils.AppDialog
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils
import com.gingersoft.gsa.delivery_pick_mode.R
import com.gingersoft.gsa.delivery_pick_mode.databinding.ActivityOtherOrderBinding
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.PageViewModel.Companion.fragmentStatus
import com.gingersoft.gsa.delivery_pick_mode.mvp.ui.activity.SendOrderActivity
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.SectionsPagerAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.base.BaseActivity
import com.gingersoft.gsa.delivery_pick_mode.util.InjectorUtil
import com.gingersoft.gsa.delivery_pick_mode.util.getCustomColor
import com.gingersoft.gsa.delivery_pick_mode.util.setState
import com.jess.arms.mvp.IPresenter
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton
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 DeliveryOrderMainActivity : BaseActivity<IPresenter>(), View.OnClickListener {

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

    //標籤文字
    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 layoutHeight: Float = 0F
    private var btnHeight: Float = 0F

    var bind: DataNotificationService.MyBind? = null

    //最後一次長連接過來的消息類型
    var lastMsgType: Int = 0

    //是否展開餐廳營業信息
    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 val functionByResModule by lazy {
        FunctionManager.getDefault().getFunctionByResModule(this, FunctionManagerConstants.takeaway::class.java, FunctionManagerConstants.takeaway.takeawayMain, "btn")
    }

    //關閉心跳的廣播
    lateinit var mReceiver: ClearHeartBroadcastReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //初始化廣播
        initBroadcast()
        //綁定視圖
        val binding: ActivityOtherOrderBinding = DataBindingUtil.setContentView(this, R.layout.activity_other_order)
        //初始化超時時間
        initOutTime()
        //初始化心跳長連接
        initWebSocket()
        //初始化標題欄
        initAppTop()
        //初始化切換餐廳狀態
        initSwitchRestStatus()
        initViewPager()
        initTabs()
        //搜索
        searchMethod()
        //獲取餐廳營業信息展示欄的高度
        initInfoHeight()
        initOrderCheckedState()
        //初始化自動接單選中
        cb_takeaway_auto_receiving_orders.isChecked = RestaurantExpandInfoUtils.getValue<Boolean>(ExpandConstant.TakeawayAutoOrder, false)
        //自動接單按鈕點擊事件
        cb_takeaway_auto_receiving_orders.setOnCheckedChangeListener { _, isChecked ->
            RestaurantExpandInfoUtils.setValue(ExpandConstant.TakeawayAutoOrder, isChecked)
            pageViewModel.autoReceiver = isChecked
        }
        pageViewModel.apply {
            autoReceiver = cb_takeaway_auto_receiving_orders.isChecked
            //獲取配送員信息
            getDeliveryInfo()
            //獲取餐廳營業信息與預約單數量信息
            getOrderStatistics(fragmentStatus[0])
            //獲取餘額信息
            getBalance(RestaurantInfoManager.newInstance().brandId)
            //第一次獲取數據
            getCurrentPageOrderList()
            //獲取每個狀態的訂單數量
            pageViewModel.getOrderGroupNum()
            //餐廳營業信息刷新監聽
            restaurantBusinessInfo.observe(this@DeliveryOrderMainActivity, Observer {
                binding.data = it
                //外送訂單數
                sb_takeaway.max = if (it.maxOrderTakeaway == 0) 1 else it.maxOrderTakeaway
                //即時單和預約單
                val orderAppointment = it.orderAppointment
                //即時單數量
                tv_immediate_order_num.visibility = View.VISIBLE
                tv_immediate_order_num.text = orderAppointment.immediateNumber.toString()
                //預約單單數
                tv_booking_order_num.visibility = View.VISIBLE
                tv_booking_order_num.text = orderAppointment.reservationNumber.toString()
                //預約單時間
                tv_booking_order.text = String.format(getString(R.string.str_reservation_time), orderAppointment.reservationConfigTime)
                //刷新餐廳營業狀態
                restaurantState.postValue(it.openStatus)
            })
            //餘額刷新監聽
            balanceBean.observe(this@DeliveryOrderMainActivity, Observer {
                it?.data?.let { data ->
                    tv_balance.text = "餘額：${data.balance}" + "（保證金: ${data.bond} )"
                    if (data.balance <= data.threshold) {
                        //提示餘額不足
                        tv_balance.setTextColor(getCustomColor(R.color.theme_red_color))
                    } else {
                        tv_balance.setTextColor(getCustomColor(R.color.theme_333_color))
                    }
                }
            })
        }
    }

    /**
     * 初始化監聽心跳廣播
     */
    private fun initBroadcast() {
        val mFilter = IntentFilter(AppConstans.CLEAR_ORDER_RECEIVING_HEART)
        mReceiver = ClearHeartBroadcastReceiver()
        registerReceiver(mReceiver, mFilter)
    }

    /**
     * 獲取高度用於收起展開
     */
    private fun initInfoHeight() {
        cl_order_info.post {
            layoutHeight = cl_order_info.height.toFloat()
        }
        btn_open_or_close_info.post {
            btnHeight = btn_open_or_close_info.height.toFloat()
        }
    }

    /**
     * 初始化即時單，預約單選中狀態
     */
    private fun initOrderCheckedState() {
        layout_immediate_order.setOnClickListener {
            it.background = ContextCompat.getDrawable(this, R.drawable.shape_left_themecolor_radius_btn)
            layout_booking_order.background = ContextCompat.getDrawable(this, R.drawable.shape_right_white_radius_btn)
            tv_immediate_order.setTextColor(ContextCompat.getColor(this, R.color.white))
            tv_booking_order.setTextColor(ContextCompat.getColor(this, R.color.theme_333_color))
            pageViewModel.appointmentType = 0
            getCurrentPageOrderList()
        }
        layout_booking_order.setOnClickListener {
            it.background = ContextCompat.getDrawable(this, R.drawable.shape_right_themecolor_radius_btn)
            layout_immediate_order.background = ContextCompat.getDrawable(this, R.drawable.shape_left_white_radius_btn)
            tv_booking_order.setTextColor(ContextCompat.getColor(this, R.color.white))
            tv_immediate_order.setTextColor(ContextCompat.getColor(this, R.color.theme_333_color))
            pageViewModel.appointmentType = 1
            getCurrentPageOrderList()
        }
    }

    private fun initViewPager() {
        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager, ints)
        view_pager.adapter = sectionsPagerAdapter
        view_pager.offscreenPageLimit = 1
        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) {
                //每次切換時去獲取訂單列表
                pageViewModel.getNewOrderList(1, fragmentStatus[position], PageViewModel.fragmentType[position])
                //只有全部||待確認 狀態下，才查詢即時單、預約單數量
                //控制即時單預約單layout的顯示與隱藏
                if (position != 0 && position != 1) {
                    layout_order_type.visibility = View.GONE
                } else {
                    pageViewModel.getOrderStatistics(fragmentStatus[position])
                    layout_order_type.visibility = View.VISIBLE
                }
            }
        })
    }

    private fun initOutTime() {
        //初始化外送接單超時時間，如果超過這個時間未接單，這個訂單會顯示超時
        pageViewModel.timeOut = RestaurantExpandInfoUtils.getValue(ExpandConstant.OrderReceivingTimeout, 0)
    }

    /**
     * 初始化viewpager的tab指示器
     */
    private fun initTabs() {
        tabs.setupWithViewPager(view_pager)
        for (i in ints.indices) {
            //获取每一个tab对象
            val tabAt = tabs.getTabAt(i)
            tabAt?.let {
                //将每一个条目设置我们自定义的视图
                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)
                mTvTitle.setText(ints[i])
                mNumber.text = "0"
                //設置不同的顏色
                mNumber.setTextColor(getCustomColor(colors[i]))
                //添加觀察者
                while (pageViewModel.mOrderNum.size <= i) {
                    pageViewModel.mOrderNum.add(MutableLiveData())
                }
                //綁定監聽，數量發生變化時修改顯示數據
                pageViewModel.mOrderNum[i].observe(this, Observer {
                    mNumber.text = it.toString()
                })
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchMethod() {
        iv_search_order.setOnClickListener {
            //搜索
            if (TextUtil.isNotEmptyOrNullOrUndefined(ed_order_num_search)) {
                pageViewModel.phone = ed_order_num_search.text.toString()
                getCurrentPageOrderList()
            } else {
                ToastUtils.show(this@DeliveryOrderMainActivity, "請輸入手機號或訂單號")
            }
        }
    }

    private var restaurantPopup: QMUIPopup? = null

    /**
     * 切換餐廳狀態按鈕
     */
    private fun initSwitchRestStatus() {
        val stateBg = GradientDrawable()
        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) {
        if (state != 0 && state != 2) {
            pageViewModel.updateRestOpenStatus(state)
        } else {
            //暫停接單，彈窗向用戶確認是否關閉
            object : DialogUtils(this, R.layout.other_order_pause_orders) {
                override fun initLayout(hepler: ViewHepler, dialog: Dialog) {
                    hepler.getView<TextView>(R.id.tv_dialog_confirm).setOnClickListener {
                        it.isClickable = false
                        pageViewModel.updateRestOpenStatus(state)
                        dialog.dismiss()
                    }
                    hepler.getView<TextView>(R.id.tv_dialog_cancel).setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }.show()
        }
        restaurantPopup?.dismiss()
    }

    /**
     * 初始化長連接
     */
    private fun initWebSocket() {
        //開啟webSocket
        val service = Intent(applicationContext, DataNotificationService::class.java)
        val notification: NotificationManagerCompat = NotificationManagerCompat.from(this)
        if (!notification.areNotificationsEnabled()) {
            //未開啟通知權限
            AppDialog().showTipDialog(this, "檢測到通知權限未打開，建議打開，否則會影響正常使用！") { _, d ->
                d.dismiss()
                val intent = Intent()
                when {
                    SDK_INT >= Build.VERSION_CODES.O -> {
                        intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
                        intent.putExtra("android.provider.extra.APP_PACKAGE", this@DeliveryOrderMainActivity.packageName)
                    }
                    SDK_INT >= Build.VERSION_CODES.LOLLIPOP -> {  //5.0
                        intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
                        intent.putExtra("app_package", this@DeliveryOrderMainActivity.packageName)
                        intent.putExtra("app_uid", this@DeliveryOrderMainActivity.applicationInfo.uid)
                        startActivity(intent)
                    }
                    SDK_INT == Build.VERSION_CODES.KITKAT -> {  //4.4
                        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                        intent.addCategory(Intent.CATEGORY_DEFAULT)
                        intent.data = Uri.parse("package:" + this@DeliveryOrderMainActivity.packageName)
                    }
                    SDK_INT >= 15 -> {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                        intent.data = Uri.fromParts("package", this@DeliveryOrderMainActivity.packageName, null)
                    }
                }
                startActivity(intent)
            }
        } else {
            if (SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(service)
            } else {
                startService(service)
            }
        }
        bindService(service, serviceConnection, Context.BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        bind?.setOnPostCallBack(null)
        bind?.execute {}
        unregisterReceiver(mReceiver)
        unbindService(serviceConnection)
    }


    private var serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            bind = service as DataNotificationService.MyBind
            bind?.let { it ->
                it.setOnPostCallBack(object : PostCallBack {
                    override fun callBack(type: Int) {
                        //-1斷開連接,\n-2:消息傳輸錯誤,\n0:連接消息,\n1：登錄通知,\n2：登出通知,\n3：外賣送單通知,\n4：自取送單通知,\n5:歷史訂單通知,\n6:修改訂單狀態通知,\n7:支付成功通知"
                        if (type == 3 || type == 4 || type == 5
                                || type == 6 || type == 7) {
                            //上次是未確認訂單，本次的提示還是未確認訂單，就不刷新本地頁面
                            if (!(lastMsgType == 5 && type == 5)) {
                                getCurrentPageOrderList()
                                // 刷新餘額
                                pageViewModel.getBalance(RestaurantInfoManager.newInstance().brandId)
                            }
                            lastMsgType = type
                            // 選擇了自動接單，有訂單來就接單
                            if (cb_takeaway_auto_receiving_orders.isChecked) {
                                //查詢待確定的訂單id
                                pageViewModel.getToBeConfirmedOrderIds()
                            }
                            //獲取每個狀態的訂單數量
                            pageViewModel.getOrderGroupNum()
                            //查詢預約單和即時單數量
                            pageViewModel.getOrderStatistics(fragmentStatus[view_pager.currentItem])
                        }
                    }
                })
                it.execute {
                    if (it) {
                        ivDisconnectView.visibility = View.VISIBLE
                    } else {
                        ivDisconnectView.visibility = View.INVISIBLE
                    }
                }
                it.jumpActivity = this@DeliveryOrderMainActivity::class.java
            }
        }

        override fun onServiceDisconnected(name: ComponentName) {
        }
    }

    /**
     * 獲取當前頁面訂單列表
     */
    private fun getCurrentPageOrderList() {
        pageViewModel.getNewOrderList(1, fragmentStatus[view_pager.currentItem], PageViewModel.fragmentType[view_pager.currentItem])
    }

    /**
     * 顯示或收起餐廳營業信息
     */
    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
                        tv_balance.visibility = View.VISIBLE
                    } else {
                        text = "查看詳情"
                        background = btnCloseBg
                        layout_search_info.visibility = View.GONE
                        layout_today_order_info.visibility = View.GONE
                        tv_balance.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
    lateinit var ivDisconnectView: QMUIAlphaImageButton

    /**
     * 初始化標題欄
     */
    private fun initAppTop() {
        //獲取功能權限
        val newOrderFunction = FunctionManager.getFunctionByKey(functionByResModule, FunctionManagerConstants.takeaway.TAKEAWAY_NEW_ORDER)
        val historyOrderFunction = FunctionManager.getFunctionByKey(functionByResModule, FunctionManagerConstants.takeaway.TAKEAWAY_HISTORY_ORDER)
        val openCashBoxFunction = FunctionManager.getFunctionByKey(functionByResModule, FunctionManagerConstants.takeaway.TAKEAWAY_OPEN_CASH_BOX)
        //顯示餐廳名
        qm_other_order_bar.setTitle(RestaurantInfoManager.newInstance().restaurantName)
        qm_other_order_bar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener { finish() }
        //至少要有一個按鈕的權限，才添加右側按鈕
        if (newOrderFunction != null || historyOrderFunction != null || openCashBoxFunction != null) {
            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(this)
                    val mTvHistoryOrder = view.findViewById<QMUIAlphaTextView>(R.id.tv_history_order)
                    mTvHistoryOrder.setState(historyOrderFunction != null)
                    mTvHistoryOrder.setOnClickListener(this)

                    val mTvOpenCashBox = view.findViewById<QMUIAlphaTextView>(R.id.tv_open_cash_box);
                    mTvOpenCashBox.setOnClickListener(this)
                    mTvOpenCashBox.setState(openCashBoxFunction != null)

                    view.findViewById<QMUIAlphaTextView>(R.id.tv_check_log).setOnClickListener(this)

                    val tvNewOrder = view.findViewById<QMUIAlphaTextView>(R.id.tv_new_order);
                    tvNewOrder.setState(newOrderFunction != null)
                    tvNewOrder.setOnClickListener(this)
                } else {
                    pop?.show(it)
                }
            }
        }
        ivDisconnectView = qm_other_order_bar.addRightImageButton(R.drawable.ic_heart_disconnect, R.id.topbar_heart_disconnect)
        ivDisconnectView.visibility = View.INVISIBLE
        qm_other_order_bar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color))
    }

    inner class ClearHeartBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 1001) {
            val doubleExtra = data?.getDoubleExtra("deliveryAmount", 0.0)
            pageViewModel.balanceBean.value?.data?.let {
                if (doubleExtra != null) {
                    it.balance -= doubleExtra
                    pageViewModel.balanceBean.postValue(pageViewModel.balanceBean.value)
                }
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (v.id) {
                R.id.tv_delivery_setting -> {
                    //備送設置
                    startActivity(Intent(this, DeliverySettingActivity::class.java))
                    pop!!.dismiss()
                }
                R.id.tv_history_order -> {
                    //歷史訂單
                    startActivity(Intent(this, HistoryOrderActivity::class.java))
                    pop!!.dismiss()
                }
                R.id.tv_open_cash_box -> {
                    //開錢箱
                    pageViewModel.openCashBox()
                    pop!!.dismiss()
                }
                R.id.tv_check_log -> {
                    //查看日誌
                    startActivity(Intent(this, LogActivity::class.java))
                    pop!!.dismiss()
                }
                R.id.tv_new_order -> {
                    //新訂單
                    BaseOrder.orderType = TAKEAWAY_TYPE
                    CC.obtainBuilder(com.gingersoft.gsa.cloud.component.ComponentName.COMPONENT_TABLE)
                            .setActionName("showMealStandActivity")
                            .build()
                            .call()
                    SPUtils.remove(SendOrderActivity.MEMBER_NAME_KEY)
                    SPUtils.remove(SendOrderActivity.MEMBER_PHONE_KEY)
                    SPUtils.remove(SendOrderActivity.MEMBER_ADDRESS_KEY)
                    pop!!.dismiss()
                }
            }
        }
    }
}