package com.lukouguoji.gnc.viewModel

import android.util.Log
import androidx.lifecycle.*
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.google.zxing.common.StringUtils
import com.lukouguoji.gnc.model.GuoneiOutWaybill
import com.lukouguoji.module_base.http.user.UserNetwork
import kotlinx.coroutines.Dispatchers
import retrofit2.await

class GoutStartViewModel : ViewModel() {
    val guoneiOutWaybill = GuoneiOutWaybill()
    var waybillFormNetWork = JSONObject()

    var agentCodeList = JSONArray()
    var businessList = JSONArray()
    var specialCodeList = JSONArray()
    var dgrDetailList = JSONArray()
    var dgrList = JSONArray()
    //板车上的货物净重
    var netWeight=0f
    //板车上的件数
    var carpc=0
    //板车所在航班
    var carFno=""
    //板车上的体积
    var carVolume=0f
    private val wbIdData = MutableLiveData<WaybillParam>()
    private val agentCodeLiveData = MutableLiveData<String>()
    private val businessLiveData = MutableLiveData<String>()
    private val specialCodeLiveData = MutableLiveData<String>()
    private val dangerLiveData = MutableLiveData<String>()
    private  var weightName=""
    private val weightDataLiveData = MutableLiveData<String>()
    inner class WaybillParam(val wbId: Int, val wbNo: String?)

    val waybillLiveData = Transformations.switchMap(wbIdData) { param ->
        liveData(Dispatchers.IO) {
            try {
                var response = JSONObject()
                if (param.wbId != -9999) {
                    response = UserNetwork.queryWbById(param.wbId)
                } else if (param.wbNo != null) {
                    response = UserNetwork.queryWbByNo(param.wbNo)
                } else {
                }
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }
    fun setWeightName(name :String)
    {
        weightName=name
    }
    fun queryWaybillById(wbId: Int, wbNo: String?) {
        wbIdData.value = WaybillParam(wbId, wbNo)
    }



    fun agentCode(time: String) {
        agentCodeLiveData.value = time
    }
    fun weightData(value: String) {
        weightDataLiveData.postValue(value)
    }

  var   weightThread=  Thread {
        while (true) {
            try {
                if(!weightName.equals(""))
                {
                    var res=  UserNetwork.getWeightData(weightName)
                  var repsonse=  res.execute()
                  var xml:StringBuffer= StringBuffer(repsonse.body().toString())
                    var str=">"
                    var len=str.length
                    var start=xml.indexOf(str)
                  //  xml = xml.replace(0,1,"")
                    xml = xml.replace(0,start+len,"")
                    xml = xml.replace(0,start+len+1,"")
                   // xml=   xml.replace(0,len,"")
                  //  Log.i("WeightThread0",xml.toString())
                    var end =xml.indexOf("</decimal>")
                 xml=   xml.replace(end,xml.length,"")
                 //   Log.i("WeightThread",xml.toString())
                   // val str = "kotlin very good"
                   // str.first{ it == 'o' }
                    weightData(xml.toString())
                }
            }catch ( e:Exception){
                Log.e("weightThread1", e.stackTraceToString())
            }
        try {
            Thread.sleep(1000)
        }catch ( e:Exception){
            Log.e("weightThread2", e.stackTraceToString())
        }


        }
    } as Thread
    val weightDataObserver = Transformations.switchMap(weightDataLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                emit(weightDataLiveData.value.toString())
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }
    val agentCodeObserver = Transformations.switchMap(agentCodeLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.agentCodeGnc()
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun business(type: String) {
        businessLiveData.value = type
    }

    val businessObserver = Transformations.switchMap(businessLiveData) { type ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.business(type)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun specialCode(time: String) {
        specialCodeLiveData.value = time
    }

    val specialCodeObserver = Transformations.switchMap(specialCodeLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.specialCode()
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun danger(time: String) {
        dangerLiveData.value = time
    }

    val dangerObserver = Transformations.switchMap(dangerLiveData) { _ ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.danger()
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }
        }
    }

    private val queryActiveCarLivaData = MutableLiveData<String>()

    val queryActiveCarObserver = Transformations.switchMap(queryActiveCarLivaData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.queryActiveCar(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun queryActiveCar(uld: String) {
        queryActiveCarLivaData.value = uld
    }

    private val completedLiveData = MutableLiveData<JSONObject>()

    val completedObserver = Transformations.switchMap(completedLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.completed(param!!)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun completed(guoneiOutWaybill: GuoneiOutWaybill) {
        val jsonObject = waybillFormNetWork
        jsonObject["activeId"] = guoneiOutWaybill.activeId
        jsonObject["agentCode"] = guoneiOutWaybill.agentCode
        jsonObject["awbType"] = guoneiOutWaybill.awbType
        jsonObject["businessType"] = guoneiOutWaybill.businessType
        jsonObject["carNo"] = guoneiOutWaybill.uld
        jsonObject["fdate"] = guoneiOutWaybill.fdate
        jsonObject["fno"] = guoneiOutWaybill.fno
        jsonObject["carrier"] = guoneiOutWaybill.carrier
        jsonObject["mawbId"] = guoneiOutWaybill.mawbId
        jsonObject["pc"] = guoneiOutWaybill.pc
        jsonObject["remark"] = guoneiOutWaybill.remark
        jsonObject["spCode"] = guoneiOutWaybill.spCode
        jsonObject["volDetail"] = guoneiOutWaybill.volDetail
        jsonObject["volume"] = guoneiOutWaybill.volume
        jsonObject["wbNo"] = guoneiOutWaybill.wbNo
        jsonObject["weight"] = guoneiOutWaybill.weight
        jsonObject["dgrDetail"] = guoneiOutWaybill.dgrDetail
        jsonObject["range"] = guoneiOutWaybill.range
        jsonObject["goods"] = guoneiOutWaybill.goods
        //todo 增加uld自重、uld
        jsonObject["uldStr"] = guoneiOutWaybill.uldStr
        jsonObject["uldSelfWeight"] = guoneiOutWaybill.uldSelfWeight
        completedLiveData.value = jsonObject
    }


    private val dividedLiveData = MutableLiveData<JSONObject>()

    val dividedObserver = Transformations.switchMap(dividedLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                val response = UserNetwork.divided(param!!)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun divided(guoneiOutWaybill: GuoneiOutWaybill) {
        val jsonObject = waybillFormNetWork
        jsonObject["activeId"] = guoneiOutWaybill.activeId
        jsonObject["agentCode"] = guoneiOutWaybill.agentCode
        jsonObject["awbType"] = guoneiOutWaybill.awbType
        jsonObject["businessType"] = guoneiOutWaybill.businessType
        jsonObject["carNo"] = guoneiOutWaybill.uld
        jsonObject["fdate"] = guoneiOutWaybill.fdate
        jsonObject["fno"] = guoneiOutWaybill.fno
        jsonObject["carrier"] = guoneiOutWaybill.carrier
        jsonObject["mawbId"] = guoneiOutWaybill.mawbId
        jsonObject["pc"] = guoneiOutWaybill.pc
        jsonObject["remark"] = guoneiOutWaybill.remark
        jsonObject["spCode"] = guoneiOutWaybill.spCode
        jsonObject["volDetail"] = guoneiOutWaybill.volDetail
        jsonObject["volume"] = guoneiOutWaybill.volume
        jsonObject["wbNo"] = guoneiOutWaybill.wbNo
        jsonObject["weight"] = guoneiOutWaybill.weight
        jsonObject["dgrDetail"] = guoneiOutWaybill.dgrDetail
        dividedLiveData.value = jsonObject
    }

    /**
     *  托盘编号，校验平板车重量
     */
    private val updateFlatcarGncStartReceiveLiveData = MutableLiveData<JSONObject>()
    val updateFlatcarGncStartReceiveObserver = Transformations.switchMap(updateFlatcarGncStartReceiveLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.updateFlatcarGncStartReceive(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun updateFlatcarGncStartReceive(carId: String, carWeight: Double) {
        val param = JSONObject()
        param["carId"] = carId
        param["carWeight"] = carWeight
        updateFlatcarGncStartReceiveLiveData.value = param
    }

    /**
     *  托盘编号，查询托盘自重
     */
    private val queryFlatcarGjcReceiveLiveData = MutableLiveData<String>()
    val queryFlatcarGjcReceiveObserver = Transformations.switchMap(queryFlatcarGjcReceiveLiveData) { param ->
        liveData(Dispatchers.IO) {
            try {
                var response = UserNetwork.queryFlatcarGjcReceive(param)
                emit(response)
            } catch (e: Exception) {
                Log.e("GoutStartViewModel", e.stackTraceToString())
            }

        }
    }

    fun queryFlatcarGjcReceive(id: String) {
        queryFlatcarGjcReceiveLiveData.value = id
    }
}