package com.jld.vod.view.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.jld.vod.R
import com.jld.vod.base.BaseFragment
import com.jld.vod.model.bean.BaseBean
import com.jld.vod.model.bean.CarInfoBean
import com.jld.vod.model.bean.CarSiteAllBean
import com.jld.vod.model.event.MapsEvent
import com.jld.vod.model.event.SiteEvent
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.view.MapsActivity
import com.jld.vod.viewmodel.MapsViewModel
import com.joketng.timelinestepview.LayoutType
import com.joketng.timelinestepview.OrientationShowType
import com.joketng.timelinestepview.TimeLineState
import com.joketng.timelinestepview.adapter.TimeLineStepAdapter
import com.joketng.timelinestepview.view.TimeLineStepView
import com.wrbug.timeline.TimeLineView
import com.xuexiang.xpage.annotation.Page
import com.xuexiang.xpage.enums.CoreAnim
import com.xuexiang.xui.widget.actionbar.TitleBar
import kotlinx.android.synthetic.main.fragment_maps.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File


@Page(anim = CoreAnim.none)
class MapsFragment : BaseFragment() {
    private lateinit var btMaps : ImageView

    private lateinit var mapsViewModel: MapsViewModel
    private val sitedata: MutableList<String> = ArrayList()
    private var mTimeLineView:TimeLineView ?= null
    val listContent = mutableListOf<com.joketng.timelinestepview.bean.BaseBean>()
    private lateinit var mrvHorizontal:TimeLineStepView
    private var localsite : Int = 0
    private var flagsite: Boolean = false

    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1->{
                    try {
                        var resite = msg.arg1 - 1 //实时传过来的站点下标
                        //LogUtils.logD("localsite=$localsite $flagsite" + "==" + resite)
                        if (flagsite) {
                            //更新到站进度
                            listContent[resite].timeLineState = TimeLineState.CURRENT//移动到当前站点
                            listContent[localsite].timeLineState = TimeLineState.ACTIVE//改变原来站点状态
                            initView(LayoutType.LEFT)
                            flagsite=false
                            localsite = resite
                        }else{
                            if (resite != localsite)
                            {
                               // localsite = resite
                                flagsite = true
                            }
                        }
                    }catch (e:Exception){
                        e.printStackTrace()
                    }
                }
            }
        }
    }
    override fun getLayoutId(): Int {
        return R.layout.fragment_maps
    }

    override fun initViews() {
        //广播值
        EventBus.getDefault().register(this)

        btMaps = findViewById(R.id.bt_look_maps)
        val region = SharedPrefUtils.getString(activity,"region")
        val SiteEvent = SharedPrefUtils.getInt(activity,"SiteEvent")
        //初始化viewmodel
        mapsViewModel = ViewModelProviders.of(this)
            .get(MapsViewModel::class.java)
        val language_lid =SharedPrefUtils.getString(activity,"language_lid")

        mTimeLineView = findViewById(R.id.timeLineView3) as TimeLineView
        mrvHorizontal = findViewById(R.id.rvHorizontal)

        //获取车辆信息
        mapsViewModel.getLanguage()

        //监听车辆信息
        val observer3 = Observer<List<CarInfoBean>> { it->
            if(it != null)
            {
                mapsViewModel.findCarSiteAll(it[0].ciId,language_lid.toLong())
            }
        }
        mapsViewModel.carInfoliveData.observe(this, observer3)

        //本地如果没有地图则下载地图
        val mapFile = File(activity!!.getExternalFilesDir(null), region + ".map")
        if (mapFile.exists())
        {
            btMaps.setOnClickListener {
                val intent = Intent(context,MapsActivity::class.java)
                startActivity(intent)
            }
        }else{
            Toast.makeText(activity,"no map",Toast.LENGTH_LONG).show()
        }

        //监听站点列表数据
        val observer = Observer<BaseBean<List<CarSiteAllBean>>> { res ->

            when (res?.code) {
                BaseBean.SUCCESS -> {
                    if (res.data!!.size==0)
                    {
                        initTimeLine()
                    }else{

                        for((index,data) in res.data.withIndex())
                        {

                           // sitedata.add(data.name)
                            localsite = SiteEvent-1
                            if (index == localsite)
                            {
                                    listContent.add(
                                        com.joketng.timelinestepview.bean.BaseBean(
                                            leftTitle = "",
                                            leftTime = data.name,
                                            rightTitle = "",
                                            rightTime = "",
                                            timeLineState = TimeLineState.CURRENT
                                        )
                                    )
                            }else{
                                    listContent.add(
                                        com.joketng.timelinestepview.bean.BaseBean(
                                            leftTitle = "",
                                            leftTime = data.name,
                                            rightTitle = "",
                                            rightTime = "",
                                            timeLineState = TimeLineState.ACTIVE
                                        )
                                    )
                                }
                        }
                        LogUtils.logD("observer"+listContent)
                        initView(LayoutType.LEFT)

                    }
                    finishLoading()
                }
                BaseBean.ERROR -> {
                    finishLoading()
                    Toast.makeText(activity, res.message, Toast.LENGTH_SHORT).show()
                }
                BaseBean.LOADING -> showLoading()
            }
        }
        mapsViewModel.carSiteLiveDataBean.observe(this, observer)
    }
    private fun initView(type: LayoutType) {
        mrvHorizontal.initData(listContent, OrientationShowType.CENTER_HORIZONTAL,
            object : TimeLineStepView.OnInitDataCallBack{
                override fun onBindDataViewHolder(holder: TimeLineStepAdapter.CustomViewHolder, position: Int) {
                    holder.tvRightTitle.setTextColor(ContextCompat.getColor(context!!, R.color.white))
                    holder.tvLeftTitle.setTextColor(ContextCompat.getColor(context!!, R.color.white))
                    holder.tvRightTime.textSize = 16f
                    holder.tvLeftTime.textSize = 16f
                    holder.tvRightTime.setTextColor(ContextCompat.getColor(context!!, R.color.white))
                    holder.tvLeftTime.setTextColor(ContextCompat.getColor(context!!, R.color.white))

                }

                override fun createCustomView(leftLayout: ViewGroup, rightLayout: ViewGroup, holder: TimeLineStepAdapter.CustomViewHolder) {
                }

            }).setLayoutType(type)
    }
    private fun initTimeLine() {
        sitedata.add("Beijing")
        sitedata.add("London")
        sitedata.add("Shanghai")
        sitedata.add("Tokyo")
        mTimeLineView!!.setPointStrings(sitedata, 1)
    }

    override fun initTitle(): TitleBar? {
        return null
    }
    /**
     * 接收站点下标的数据
     * @param result
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getMapsStatusData(sitesort: SiteEvent) {
        val msg = Message()
        msg.what = 1
        msg.arg1 = sitesort.data
        mHandler.sendMessage(msg)

    }


    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }
}