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.core.view.isGone
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.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage
import com.gingersoft.gsa.cloud.base.utils.RestaurantExpandInfoUtils
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.cloud.base.widget.DialogUtils
import com.gingersoft.gsa.cloud.constans.AppConstans
import com.gingersoft.gsa.cloud.constans.ExpandConstant
import com.gingersoft.gsa.cloud.constans.FoodSummaryConstans.TAKEAWAY_TYPE
import com.gingersoft.gsa.cloud.constans.FunctionManagerConstants
import com.gingersoft.gsa.cloud.database.bean.Function
import com.gingersoft.gsa.cloud.function.FunctionManager
import com.gingersoft.gsa.cloud.service.GetInfoUpdateService
import com.gingersoft.gsa.cloud.service.PostCallBack
import com.gingersoft.gsa.cloud.ui.utils.AppDialog
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.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.getmColor
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 instance by lazy { this }

    private val restaurantId by lazy { GsaCloudApplication.getRestaurantId() }
    private val memberId by lazy { GsaCloudApplication.getMemberId() }

    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 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)

        val mFilter = IntentFilter(AppConstans.CLEAR_ORDER_RECEIVING_HEART)
        mReceiver = ClearHeartBroadcastReceiver()
        registerReceiver(mReceiver, mFilter)
        val binding: ActivityOtherOrderBinding = DataBindingUtil.setContentView(this, R.layout.activity_other_order)
        initOutTime()
        initWebsocket()
        initAppTop()
        initSwitchRestStatus()

        initViewPager()
        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()
        }

        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.postValue(0)
        }
        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.postValue(1)
        }
        pageViewModel.apply {
            getDeliveryInfo(restaurantId.toString(), memberId.toString())
            balanceBean.observe(this@DeliveryOrderMainActivity, Observer {
                it?.data?.let { data ->
                    tv_balance.text = "餘額：${data.balance}" + "（保證金: ${data.bond} )"
                    if (data.balance <= data.threshold) {
                        //提示餘額不足
                        tv_balance.setTextColor(getmColor(R.color.theme_red_color))
                    } else {
                        tv_balance.setTextColor(getmColor(R.color.theme_333_color))
                    }
                }
            })
            instantOrderNum.observe(this@DeliveryOrderMainActivity, Observer {
                tv_immediate_order_num.visibility = View.VISIBLE
                tv_immediate_order_num.text = it.toString()
            })
            bookingOrderNum.observe(this@DeliveryOrderMainActivity, Observer {
                tv_booking_order_num.visibility = View.VISIBLE
                tv_booking_order_num.text = it.toString()
            })
            bookingConfigTime.observe(this@DeliveryOrderMainActivity, Observer {
                tv_booking_order.text = "預約單($it" + "分)"
            })
        }
    }

    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.refreshState.postValue(position)
                if (position != 0 && position != 1) {
                    layout_order_type.visibility = View.GONE
                } else {
                    layout_order_type.visibility = View.VISIBLE
                }
            }
        })
    }

    private var colorAnimation: ValueAnimator? = null

    override fun onStart() {
        super.onStart()
        pageViewModel.getBanlance(GsaCloudApplication.getBrandId())
    }

    override fun onResume() {
        super.onResume()
        colorAnimation?.let {
            it.resume()
        }
    }

    override fun onPause() {
        super.onPause()
        colorAnimation?.let {
            it.pause()
        }
    }

    private fun initOutTime() {
        pageViewModel.timeOut = RestaurantExpandInfoUtils.getValue(ExpandConstant.OrderReceivingTimeout, 0)
    }

    /**
     * 加載餐廳營業信息
     */
    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 ints.indices) {
            //获取每一个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(ContextCompat.getColor(this@DeliveryOrderMainActivity, 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(restaurantId.toString(), viewPager.currentItem, "0", false)
//                    ToastUtils.show(this@DeliveryOrderMainActivity, "搜索到$it" + "條數據")
            } else {
                ToastUtils.show(this@DeliveryOrderMainActivity, "請輸入手機號或訂單號")
            }
        }
    }

    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) {
        if (state != 0 && state != 2) {
            pageViewModel.updateRestOpenStatus(state, restaurantId.toString())
        } 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, restaurantId.toString())
                        dialog.dismiss()
                    }
                    hepler.getView<TextView>(R.id.tv_dialog_cancel).setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }.show()
        }
        restaurantPopup?.dismiss()
    }

    private fun initWebsocket() {
        //開啟websocket
        val service = Intent(applicationContext, GetInfoUpdateService::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 {}
        cancelDialogForLoading()
        unregisterReceiver(mReceiver)
        unbindService(serviceConnection)
    }

    var bind: GetInfoUpdateService.MyBind? = null

    var lastRefreshTime: Long = 0
    private var serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            bind = service as GetInfoUpdateService.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 || type == 0) {
                            val currentTime = System.currentTimeMillis()
                            if (currentTime - lastRefreshTime > 1000) {
                                lastRefreshTime = currentTime
                                pageViewModel.refreshState.postValue(view_pager.currentItem)
                            }
                        }
                        //刷新餘額
                        pageViewModel.getBanlance(GsaCloudApplication.getBrandId())
                    }
                })
                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 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
                        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(GsaCloudApplication.getRestaurantName())
        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 -> {
                    //新訂單
                    MyOrderManage.getInstance().orderType = TAKEAWAY_TYPE
                    CC.obtainBuilder("Component.Table")
                            .setActionName("showMealStandActivity")
                            .build()
                            .call()
                    pop!!.dismiss()
                }
            }
        }
    }
}