package com.jld.vod.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.room.Room
import com.jld.vod.db.CarSiteAllDatabase
import com.jld.vod.db.CarInfoDatabase
import com.jld.vod.model.bean.*
import com.jld.vod.utils.http.RetrofitUtils

/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/7/22 17:15
 */
class MapsViewModel (app: Application)  : AndroidViewModel(app)  {

    val carinfodb = Room.databaseBuilder(app, CarInfoDatabase::class.java, "carinfo").build()
    val carsitealldb = Room.databaseBuilder(app, CarSiteAllDatabase::class.java, "carsiteall").build()
    val carSiteLiveDataBean: MutableLiveData<BaseBean<List<CarSiteAllBean>>> = MutableLiveData()
    val carInfoliveData: MutableLiveData<List<CarInfoBean>> = MutableLiveData()

    /**
     * 获取该车辆所有站点信息
     */
    fun findCarSiteAll(ciId: Long,lid: Long): MutableLiveData<BaseBean<List<CarSiteAllBean>>> {
        carSiteLiveDataBean.postValue(BaseBean.loading(null))
        RetrofitUtils.findCarSiteAll(ciId,lid,
            { t ->
                when (t.code) {
                    20000 -> {
                        if (t.data!=null)
                        {
                            Thread(Runnable{ run {
                                if (!carsitealldb.carSiteAllDao().getAll().isEmpty())
                                {
                                    carsitealldb.carSiteAllDao().delete()
                                    for ((index,e) in t.data.withIndex()){
                                        carsitealldb.carSiteAllDao().insertAll(t.data[index])
                                    }
                                }else{
                                    for ((index,e) in t.data.withIndex()){
                                        carsitealldb.carSiteAllDao().insertAll(t.data[index])
                                    }
                                }
                            }}).start()
                        }
                        carSiteLiveDataBean.postValue(BaseBean.success(t.data))
                    }
                    else -> carSiteLiveDataBean.postValue(BaseBean.error(t.message, t.data))
                }
            },
            { ex ->
               // ex.printStackTrace()
                carSiteLiveDataBean.postValue(BaseBean.error(ex.message!!, null))
            }
        )
        return carSiteLiveDataBean
    }


    /**
     * 获取车辆信息
     */
    fun getLanguage() {
        Thread(Runnable {
            carInfoliveData!!.postValue(carinfodb.carInfoDao().getAll())
        }).start()
    }
}
