package com.casic.common.detector.gd.vm

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.casic.common.detector.gd.bean.TaskMarkerLocalBean
import com.casic.common.detector.gd.extensions.getResponseMessage
import com.casic.common.detector.gd.extensions.getResponseState
import com.casic.common.detector.gd.model.MarkerFileModel
import com.casic.common.detector.gd.model.TaskModel
import com.casic.common.detector.gd.retrofit.RetrofitServiceManager
import com.casic.common.detector.gd.utils.DataBaseManager
import com.casic.common.detector.gd.utils.LocaleConstant
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import com.pengxh.kt.lite.base.BaseViewModel
import com.pengxh.kt.lite.extensions.launch
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.LoadState
import com.pengxh.kt.lite.utils.SaveKeyValues

class TaskViewModel : BaseViewModel() {

    private val kTag = "TaskViewModel"
    private val gson by lazy { Gson() }
    val markerFileResult = MutableLiveData<MarkerFileModel>()
    val taskResult = MutableLiveData<TaskModel>()
    val freeTaskResult = MutableLiveData<String>()
    val uploadTaskMarkerResult = MutableLiveData<String>()
    val executeTaskResult = MutableLiveData<String>()

    fun createFreeTask(context: Context, patrollerId: String, description: String) = launch({
        val response = RetrofitServiceManager.createFreeTask(patrollerId, description)
        if (response.getResponseState()) {
            val element = JsonParser.parseString(response)
            val jsonObject = element.asJsonObject
            freeTaskResult.value = jsonObject.get("taskId").asInt.toString()
        } else {
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
    })

    fun uploadTaskMarker(context: Context, taskId: String, ids: ArrayList<String>) = launch({
        val response = RetrofitServiceManager.uploadTaskMarker(taskId, ids)
        if (response.getResponseState()) {
            val element = JsonParser.parseString(response)
            val jsonObject = element.asJsonObject
            uploadTaskMarkerResult.value = jsonObject.get("success").asString

            //删除本地数据库
            val taskCode = SaveKeyValues.getValue(LocaleConstant.TASK_CODE, "") as String
            DataBaseManager.get.deleteLocalTaskById(taskId, taskCode)
            SaveKeyValues.putValue(LocaleConstant.TASK_ID, "")
        } else {
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
    })

    fun getMarkerFile(context: Context, userId: String, companyId: String) = launch({
        val response = RetrofitServiceManager.getMarkerFile(userId, companyId)
        if (response.getResponseState()) {
            markerFileResult.value = gson.fromJson<MarkerFileModel>(
                response, object : TypeToken<MarkerFileModel>() {}.type
            )
        } else {
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
    })

    fun getTasksByUser(context: Context, userName: String) = launch({
        val response = RetrofitServiceManager.getTasksByUser(userName)
        if (response.getResponseState()) {
            taskResult.value = gson.fromJson<TaskModel>(
                response, object : TypeToken<TaskModel>() {}.type
            )
        } else {
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
    })

    fun installLabel(
        context: Context,
        companyId: String,
        recordType: String,
        markerObjectType: String,
        pipeMaterial: String,
        pipeDiameter: String,
        depth: String,
        belowType: String,
        belowMaterial: String,
        belowDiameter: String,
        belowDepth: String,
        layStyle: String,
        area: String,
        line: String,
        road: String,
        constructTime: String,
        ownerComp: String,
        markerObjectId: String,
        markerId: String,
        markerType: String,
        markerDepth: String,
        creator: String,
        createTime: String,
        longitude: String,
        latitude: String,
        colorType: String,
        memo: String,
        realPaths: ArrayList<String>
    ) = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.installLabel(
            companyId,
            recordType,
            markerObjectType,
            pipeMaterial,
            pipeDiameter,
            depth,
            belowType,
            belowMaterial,
            belowDiameter,
            belowDepth,
            layStyle,
            area,
            line,
            road,
            constructTime,
            ownerComp,
            markerObjectId,
            markerId,
            markerType,
            markerDepth,
            creator,
            createTime,
            longitude,
            latitude,
            colorType,
            memo,
            realPaths
        )
        if (response.getResponseState()) {
            loadState.value = LoadState.Success
        } else {
            loadState.value = LoadState.Fail
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
        loadState.value = LoadState.Fail
    })

    fun uploadTask(
        context: Context, userId: String, taskId: String, taskCode: String, state: String
    ) = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.uploadTask(userId, taskId, state)
        if (response.getResponseState()) {
            loadState.value = LoadState.Success
            //工单提交之后，并且状态是2，删除本地Task记录
            if (state == "2") {
                "工单${taskId}已提交！".show(context)
                //删除本地数据库
                DataBaseManager.get.deleteLocalTaskById(taskId, taskCode)
                SaveKeyValues.putValue(LocaleConstant.TASK_ID, "")

                val element = JsonParser.parseString(response)
                val jsonObject = element.asJsonObject
                executeTaskResult.value = jsonObject.get("success").asString
            } else {
                Log.d(kTag, "uploadTask: 仅执行工单，不删除本地工单数据")
            }
        } else {
            loadState.value = LoadState.Fail
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
        loadState.value = LoadState.Fail
    })

    fun uploadEvent(
        context: Context, taskId: String, event: String, realPaths: ArrayList<String>
    ) = launch({
        loadState.value = LoadState.Loading
        val response = RetrofitServiceManager.uploadEvent(taskId, event, realPaths)
        if (response.getResponseState()) {
            loadState.value = LoadState.Success
        } else {
            loadState.value = LoadState.Fail
            response.getResponseMessage().show(context)
        }
    }, {
        it.printStackTrace()
        loadState.value = LoadState.Fail
    })

    fun uploadMarker(context: Context, marker: TaskMarkerLocalBean) = launch({
        //主键ID代替MarkerId
        RetrofitServiceManager.uploadMarker(marker.id.toString())
        "标识器${marker.markerId}已探测！".show(context)
        DataBaseManager.get.updateLocalTaskMarkerState(marker)
    }, {
        it.printStackTrace()
    })
}