package com.lukouguoji.module_base.http.net

import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.R
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.util.HandlerUtils
import dev.DevUtils
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class DiBangWeightModel {

    // 地磅重量
    val weight = MutableLiveData<String>()

    val interval = 1000L

    var key = ""
        set(value) {
            field = value
            if (field.isNotEmpty()) {
                startLooperGet()
            }
        }

    private val action = {
        getWeightData()
    }

    fun startLooperGet() {
        HandlerUtils.removeRunnable(action)
        getWeightData()
    }

    fun cancelLooperGet() {
        showLog("停止循环获取")
        key = ""
        HandlerUtils.removeRunnable(action)
    }

    private fun getWeightData() {
        if (key.isEmpty()) {
            return
        }
        thread {
            //第一步：创建服务地址
//            val url = URL(DevUtils.getContext().resources.getString(R.string.weight_url))
            val url = URL(SharedPreferenceUtil.getString(Constant.Share.ipAddressWeight))

            showLog("url: $url")
            //第二步：打开一个通向服务端地址的连接
            val connection = url.openConnection() as HttpURLConnection

            //设置参数
            connection.requestMethod = "POST"
            connection.setRequestProperty("content-type", "text/xml;charset=utf-8")

            //设置输入输出
            connection.doOutput = true
            connection.doInput = true

            //准备SOAP数据，发送请求
            val soapxml = getXML(key)

            showLog("请求体: $soapxml")

            val out = connection.outputStream
            val writer = OutputStreamWriter(out, "utf-8")
            writer.write(soapxml)
            writer.close()
            out.close()

            //第五步接收服务端响应并打印
            showLog("返回码 - ${connection.responseCode}")
            if (connection.responseCode == HttpURLConnection.HTTP_OK) {
                val input = connection.inputStream
                val reader = InputStreamReader(input, "utf-8")
                val buffered = BufferedReader(reader)
                var temp: String? = null
                val sb = StringBuilder()
                while ((buffered.readLine().also { temp = it }) != null) {
                    sb.append(temp)
                }
                buffered.close()
                reader.close()
                input.close()
                val targetKey = "<resultWeight>"
                if (sb.indexOf(targetKey) >= 0) {
                    val w = sb.substring(
                        sb.indexOf(targetKey) + targetKey.length,
                        sb.indexOf("</resultWeight>")
                    )
                    showLog("获取重量: $w")
                    weight.postValue(w)
                }

                showLog("请求结果: $sb")
            }
            if (key.isNotEmpty()) {
                HandlerUtils.postRunnable(action, interval)
            }
        }
    }

    fun getXML(key: String): String {
        return ("<?xml version=\"1.0\" ?>"
                + "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<S:Body>"
                + "<ns2:queryWeight xmlns:ns2=\"http://service.cn_lc\">"
                + "<key>" + key + "</key>"
                + "</ns2:queryWeight>"
                + "</S:Body>"
                + "</S:Envelope>")
    }

    private fun showLog(message: String) {
        loge("获取地磅重量 : $message")
    }

}