package com.lukouguoji.mit.viewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.module_base.common.String.emptyToNull
import com.lukouguoji.module_base.http.user.UserNetwork
import kotlinx.coroutines.Dispatchers
import kotlin.collections.set

class AccidentVisaViewModel : ViewModel() {

    private val logName = "AccidentVisaViewModel"

    /**
     * 分页搜索
     */
    private val searchParam = MutableLiveData<JSONObject>()
    val searchParamLive = Transformations.switchMap(searchParam) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.searchVisa(param)
                emit(response)
            } catch (e: Exception) {
                Log.e(logName, e.stackTraceToString())
            }

        }
    }

    fun search(
        limit: Int,
        page: Int,
        beginDate: String,
        endDate: String,
        areaType: String,
        ieFlag: String,
        wbNo: String,
        opId: String
    ) {

        val param = JSONObject()
        param["limit"] = limit
        param["page"] = page
        param["beginDate"] = beginDate.emptyToNull()
        param["endDate"] = endDate.emptyToNull()
        param["areaType"] = areaType.emptyToNull()
        param["ieFlag"] = ieFlag.emptyToNull()
        param["wbNo"] = wbNo.emptyToNull()
        param["opId"] = opId.emptyToNull()


        searchParam.value = param
    }

    /**
     * 删除行
     */
    inner class AccidentVisaDel(val id: Int, val position: Int)

    private val deleteLineLiveData = MutableLiveData<AccidentVisaDel>()
    val deleteLineObserver = Transformations.switchMap(deleteLineLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.deleteVisa(param.id)
                response["positionDel"] = param.position
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutCollectionViewModel", e.stackTraceToString())
            }

        }
    }

    fun deleteLine(id: Int, position: Int) {
        deleteLineLiveData.value = AccidentVisaDel(id, position)
    }

}