package com.jld.vod.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.room.Room
import com.jld.vod.db.CarInfoDatabase
import com.jld.vod.db.LanguageDatabase
import com.jld.vod.model.bean.*
import com.jld.vod.utils.DateUtils
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.http.RetrofitUtils

/**
 * Create by zhaofuxin on 2020/7/14
 */
class SplashViewModel(app: Application) : AndroidViewModel(app) {

    private  var app: Application? = null
    init{ this.app = app }

    val languagedb = Room.databaseBuilder(app, LanguageDatabase::class.java, "language").build()
    val carinfodb = Room.databaseBuilder(app, CarInfoDatabase::class.java, "carinfo").build()

    val findLanguageAllliveData: MutableLiveData<BaseBean<List<LanguageBean>>> = MutableLiveData()
    //    获取车辆信息
    val carInfoliveData: MutableLiveData<BaseBean<List<CarInfoBean>>> = MutableLiveData()
    val carRunInfoliveData: MutableLiveData<BaseBean<CarRunInfoBean>> = MutableLiveData()
    val detectAppUpdatesliveData: MutableLiveData<String> = MutableLiveData()
    val previewAPKliveData: MutableLiveData<String> = MutableLiveData()

    //检测是否绑定车辆
    val eqCarliveData: MutableLiveData<String> = MutableLiveData()
    val findCarByUnboundliveData: MutableLiveData<BaseBean<List<FindCarByUnboundBean>>> = MutableLiveData()
    val bindingliveData: MutableLiveData<String> = MutableLiveData()
    val findGameByNoInstallliveData: MutableLiveData<BaseBean<List<FindGameByNoInstallBean>>> = MutableLiveData()
    val updateGameInstallStateliveData: MutableLiveData<String> = MutableLiveData()
    val findHomePageImgliveData: MutableLiveData<BaseBean<HomePageImgBean>> = MutableLiveData()
    val NuInstallGameLiveData: MutableLiveData<BaseBean<List<NuInstallGameBean>>> = MutableLiveData()
    val updateUserLiveData: MutableLiveData<Boolean> = MutableLiveData()

    /**
     * 获取所有语言信息
     */
    fun findLanguageAll(): MutableLiveData<BaseBean<List<LanguageBean>>> {
        findLanguageAllliveData.postValue(BaseBean.loading(null))
        RetrofitUtils.findLanguageAll(
                { t ->
                    when (t.code) {
                        20000 ->{
                            if (t.data!=null)
                            {
                                Thread(Runnable{ run {
                                    if (!languagedb.languageDao().getAll().isEmpty())
                                    {
                                        languagedb.languageDao().delete()
                                        for ((index,e) in t.data.withIndex()){
                                            languagedb.languageDao().insertAll(t.data[index])
                                        }
                                    }else{
                                        for ((index,e) in t.data.withIndex()){
                                            languagedb.languageDao().insertAll(t.data[index])
                                        }
                                    }
                                }}).start()
                            }
                            findLanguageAllliveData.postValue(BaseBean.success(t.data))
                        }
                        else -> findLanguageAllliveData.postValue(BaseBean.error(t.message, t.data))
                    }
                },
                { ex ->
                    findLanguageAllliveData.postValue(BaseBean.error(ex.message!!, null))
                }
        )
        return findLanguageAllliveData
    }
    /**
     * 获取车辆信息
     */
    fun getCarInfo(): MutableLiveData<BaseBean<List<CarInfoBean>>> {
        Log.i("SplashViewModel", "getCarInfo: 获取车辆信息")
        carInfoliveData.postValue(BaseBean.loading(null))
        RetrofitUtils.carInfo(
            { t ->
                when (t.code) {
                    20000 ->{
                        Log.i("SplashViewModel", "getCarInfo: 获取成功")
                        if (t.data!=null)
                        {
                            //将数据存入机子数据库
                            Thread(Runnable{ run {
                                Log.i("SplashViewModel", "getCarInfo: 存入本地")
                                if (!carinfodb.carInfoDao().getAll().isEmpty())
                                {
                                    carinfodb.carInfoDao().delete()
                                    for ((index,e) in t.data.withIndex()){
                                        carinfodb.carInfoDao().insertAll(t.data[index])
                                    }
                                }else{
                                    for ((index,e) in t.data.withIndex()){
                                        carinfodb.carInfoDao().insertAll(t.data[index])
                                    }
                                }
                            }}).start()
                        }
                        //返回订阅通知，将数据返回
                        carInfoliveData.postValue(BaseBean.success(t.data))
                    }
                    else -> carInfoliveData.postValue(BaseBean.error(t.message, t.data))
                }
            },
            { ex ->
                Log.e("SplashViewModel", "ex: 获取失败$ex")
                carInfoliveData.postValue(BaseBean.error(ex.message!!, null))
            })
        return carInfoliveData
    }
    /**
     * 获取车辆运行信息
     */
    fun getCarRunInfo(): MutableLiveData<BaseBean<CarRunInfoBean>> {
        carRunInfoliveData.postValue(BaseBean.loading(null))
        RetrofitUtils.carRunInfo(
            { t ->
                when (t.code) {
                    20000 -> {
                        if (t.data != null)
                        {
                            DateUtils.setSystemDate(t.data.date)//设置系统时间
                        }
                        carRunInfoliveData.postValue(BaseBean.success(t.data))
                    }
                    else -> carRunInfoliveData.postValue(BaseBean.error(t.message, t.data))
                }
            },
            { ex ->

                carRunInfoliveData.postValue(BaseBean.error(ex.message!!, null))
            }
        )
        return carRunInfoliveData
    }


    /**
     * 检测APP是否有更新（与云服务器交互）
     */
    fun detectAppUpdates(userId:Long,versionNum:Long): MutableLiveData<String> {
       // detectAppUpdatesliveData.postValue(null)
        RetrofitUtils.detectAppUpdates(userId,versionNum, { t ->
                when (t.code) {
                    20000 -> detectAppUpdatesliveData.postValue(t.data)
                    else -> detectAppUpdatesliveData.postValue(t.message)
                }
            }, { ex ->
                ex.printStackTrace()
                LogUtils.logD("错误数据：$ex")
                detectAppUpdatesliveData.postValue("err")
            }
        )
        return detectAppUpdatesliveData
    }

    /**
     * 下载云apk到本地服务器（与云服务器交互）
     */
    fun previewAPK(apkFile:String): MutableLiveData<String> {
        previewAPKliveData.postValue(null)
        RetrofitUtils.previewAPK(apkFile,
            { t ->
                when (t.code) {
                    20000 -> previewAPKliveData.postValue("0")
                    else -> previewAPKliveData.postValue("404")
                }
            },
            { ex ->
                ex.printStackTrace()
                previewAPKliveData.postValue(ex.message!!)
            }
        )
        return previewAPKliveData
    }


    /**
     * 检测车辆是否绑定云平台
     */
    fun eqCar(userId: Long): MutableLiveData<String> {
        LogUtils.logD("eqCartuserId"+userId)
        eqCarliveData.postValue(null)
        RetrofitUtils.eqCar(
            { t ->
                LogUtils.logD("eqCart"+t)
                when (t.code) {
                    20001 -> findCarByUnbound(userId)//previewAPKliveData.postValue("0")
                    20000 -> eqCarliveData.postValue("20000")
                    else  -> eqCarliveData.postValue("404")
                }
            },
            { ex ->
                LogUtils.logD("eqCar"+ex)
                eqCarliveData.postValue(ex.message!!)
            }
        )
        return eqCarliveData
    }


    /**
     * 获取用户未绑定车辆
     */
    fun findCarByUnbound(userId:Long): MutableLiveData<BaseBean<List<FindCarByUnboundBean>>> {
        findCarByUnboundliveData.postValue(null)
        LogUtils.logD("获取用户未绑定车辆$userId")
        RetrofitUtils.findCarByUnbound(userId,
            { t ->
                when (t.code) {

                    20000 -> {
                        LogUtils.logD("获取用户未绑定车辆$t")
                        findCarByUnboundliveData.postValue(BaseBean.success(t.data))
                    }
                    else -> findCarByUnboundliveData.postValue(BaseBean.error(t.message, t.data))
                }
            },
            { ex ->
                findCarByUnboundliveData.postValue(BaseBean.error(ex.message!!, null))
            }
        )
        return findCarByUnboundliveData
    }


    /**
     * 车辆绑定云平台
     */
    fun binding(ciId:String): MutableLiveData<String> {
        bindingliveData.postValue(null)
        RetrofitUtils.binding(ciId,
            { t ->
                when (t.code) {
                    20000 -> bindingliveData.postValue("0")
                    else -> bindingliveData.postValue("404")
                }
            },
            { ex ->
                bindingliveData.postValue(ex.message!!)
            }
        )
        return bindingliveData
    }

    /**
     * 获取未安装游戏列表
     */
    fun findGameByNoInstall(terminal:String): MutableLiveData<BaseBean<List<FindGameByNoInstallBean>>> {
        LogUtils.logD("findGameInstalledPath: 正在未安装游戏")
        findGameByNoInstallliveData.postValue(null)
        RetrofitUtils.findGameByNoInstall(terminal,
            { t ->
                when (t.code) {
                    20000 ->{
                        LogUtils.logD("findGameInstalledPath: 获取未安装游戏，$t----"+t.data)
                        findGameByNoInstallliveData.postValue(BaseBean.success(t.data))
                    }
                    else -> findGameByNoInstallliveData.postValue(BaseBean.error(t.message, t.data))
                }
            },
            { ex ->
                LogUtils.logD("获取游戏未安装，获取游戏未安装$ex")
                findGameByNoInstallliveData.postValue(BaseBean.error(ex.message!!, null))
            }
        )
        return findGameByNoInstallliveData
    }

    /**
     * 更新游戏安装状态
     */
    fun updateGameInstallState(resId: String,install: String,terminal: String): MutableLiveData<String> {
        updateGameInstallStateliveData.postValue(null)
        RetrofitUtils.updateGameInstallState(resId,install,terminal,
            { t ->
                when (t.code) {
                    20000 -> updateGameInstallStateliveData.postValue("0")
                    else -> updateGameInstallStateliveData.postValue("404")
                }
            },
            { ex ->
                updateGameInstallStateliveData.postValue(ex.message!!)
            }
        )
        return updateGameInstallStateliveData
    }

    /**
     * 获取系统主页静态资源
     */
    fun findHomePageImg(): MutableLiveData<BaseBean<HomePageImgBean>> {
        findHomePageImgliveData.postValue(null)
        RetrofitUtils.findHomePageImg(
            { t ->
                when (t.code) {
                    20000 -> findHomePageImgliveData.postValue(BaseBean.success(t.data))
                    else -> findHomePageImgliveData.postValue(BaseBean.error(t.message, t.data))
                }
            },
            { ex ->
                ex.printStackTrace()
                findHomePageImgliveData.postValue(BaseBean.error(ex.message!!, null))
            }
        )
        return findHomePageImgliveData
    }


    /**
     * 返回需要卸载的游戏
     */
    fun getNuInstallGame(terminal:String): MutableLiveData<BaseBean<List<NuInstallGameBean>>> {
        NuInstallGameLiveData.postValue(null)
        RetrofitUtils.getNuInstallGame(terminal,
                { t ->
                    when (t.code) {
                        20000 -> NuInstallGameLiveData.postValue(BaseBean.success(t.data))
                        else -> NuInstallGameLiveData.postValue(BaseBean.error(t.message, t.data))
                    }
                },
                { ex ->
                    ex.printStackTrace()
                    NuInstallGameLiveData.postValue(BaseBean.error(ex.message!!, null))
                }
        )
        return NuInstallGameLiveData
    }

    /**
     * 删除安装目录
     */
    fun delInstallPath(tiId:String): MutableLiveData<BaseBean<List<NuInstallGameBean>>> {
        NuInstallGameLiveData.postValue(null)
        RetrofitUtils.delInstallPath(tiId,
                { t ->
                    when (t.code) {
                        20000 -> NuInstallGameLiveData.postValue(BaseBean.success(t.data))
                        else -> NuInstallGameLiveData.postValue(BaseBean.error(t.message, t.data))
                    }
                },
                { ex ->
                    ex.printStackTrace()
                    NuInstallGameLiveData.postValue(BaseBean.error(ex.message!!, null))
                }
        )
        return NuInstallGameLiveData
    }
    /**
     * 绑定用户
     */
    fun updateUser(userId:String): MutableLiveData<Boolean> {
        RetrofitUtils.updateUser(userId,
                { t ->
                    when (t.code) {
                        20000 -> updateUserLiveData.postValue(true)
                        else -> updateUserLiveData.postValue(false)
                    }
                },
                { ex ->
                    ex.printStackTrace()
                    updateUserLiveData.postValue(false)
                }
        )
        return updateUserLiveData
    }
}