package com.gingersoft.gsa.other_order_mode

import android.animation.ValueAnimator
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
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.utils.toast.ToastUtils
import com.gingersoft.gsa.other_order_mode.databinding.ActivityOtherOrderBinding
import com.gingersoft.gsa.other_order_mode.service.GetInfoUpdateService
import com.gingersoft.gsa.other_order_mode.ui.main.PageViewModel
import com.gingersoft.gsa.other_order_mode.ui.main.SectionsPagerAdapter
import com.gingersoft.gsa.other_order_mode.util.InjectorUtil
import kotlinx.android.synthetic.main.activity_other_order.*


class OtherOrderActivity : AppCompatActivity() {

    private lateinit var pageViewModel: PageViewModel
    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(
            "#FF5722",
            "#009688",
            "#1E9FFF",
            "#FFB800",
            "#393D49"
    )

    private var titls: ArrayList<TextView> = ArrayList()
    private var layoutHeight: Float = 0F


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

        //開啟websocket
        var intent = Intent(this, GetInfoUpdateService::class.java)
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)

        pageViewModel = ViewModelProvider(this, InjectorUtil.getWeatherModelFactory())[PageViewModel::class.java]
        initAppTop()

        //綁定營業按鈕狀態
        pageViewModel.restaurantState.observe(this, Observer {
            btn_switch_restaurant_state.isChecked = it
            tv_restaurant_state.text = if (it) {
                resources.getString(R.string.normal)
            } else {
                resources.getString(R.string.rest)
            }
        })

        val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager, ints)
        val viewPager: ViewPager = findViewById(R.id.view_pager)
        viewPager.adapter = sectionsPagerAdapter
        viewPager.offscreenPageLimit = 4

        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(viewPager.currentItem, "0", false) {}
            } else {
                ToastUtils.show(this@OtherOrderActivity, "請輸入手機號或訂單號")
            }
        }
        tabs.setupWithViewPager(viewPager)

        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)
                titls.add(mNumber)
                mTvTitle.setText(ints[i])

                val drawable = GradientDrawable()
                drawable.setColor(Color.parseColor(colors[i]))
                drawable.cornerRadius = 5f
                mNumber.background = drawable
                mNumber.text = "0"
                while (pageViewModel.mOrderList.size <= i) {
                    pageViewModel.mOrderList.add(MutableLiveData())
                }
                pageViewModel.mOrderList[i].observe(instance, Observer {
                    mNumber.text = it.size.toString()
                })
            }
        }

        //餐廳營業信息
        pageViewModel.otherInfo.observe(this, Observer {
            binding.data = pageViewModel
            sb_takeaway.maxValue = it.MaxOrder
            sb_takeaway.progress = it.num
            sb_self.maxValue = 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()
            }
        })
        cl_order_info.post {
            layoutHeight = cl_order_info.height.toFloat()
        }
        btn_open_or_close_info.setOnClickListener {
            setOrderInfoOpenOrClose()
        }
    }

    private var serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            var 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:支付成功通知"
                    if (type == 3 || type == 4 || type == 5
                            || type == 6 || type == 7) {
                        //播放提示音
                        pageViewModel.refreshState.postValue(type)
                    }
                }
            })

        }

        override fun onServiceDisconnected(name: ComponentName) {

        }
    }


    private var isOpen: Boolean = true
    private fun setOrderInfoOpenOrClose() {
        btn_open_or_close_info.isClickable = false
        isOpen = !isOpen
        //如果是打開的，則關閉
        val heightAnimation = if (isOpen)
            ValueAnimator.ofFloat(0f, layoutHeight)
        else
            ValueAnimator.ofFloat(layoutHeight, 0f)
        heightAnimation.duration = 200
        heightAnimation.addUpdateListener { animation ->
            val `val` = animation.animatedValue as Float
            setViewHeight(cl_order_info, `val`.toInt())
            btn_open_or_close_info.text =
                    if (isOpen) {
                        "點擊收起"
                    } else {
                        "點擊展開"
                    }
            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 fun initAppTop() {
        qm_other_order_bar.setTitle(R.string.app_name)
        qm_other_order_bar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener { finish() }
        qm_other_order_bar.setBackgroundColor(resources.getColor(R.color.theme_color))
    }
}