package com.lukouguoji.gnc.page.fubang.details

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.observe
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GncFuBangBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.DetailsPageType
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.http.net.DiBangWeightModel
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.model.BluetoothDialogModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.DictUtils
import com.lukouguoji.module_base.util.PrinterUtils
import dev.utils.app.info.KeyValue
import kotlin.math.abs

class GncFuBangDetailsViewModel : BaseViewModel() {

    val pageType = MutableLiveData(DetailsPageType.Add)

    val channel = MutableLiveData("")

    val dataBean = MutableLiveData(GncFuBangBean())

    val showWeightEdit = MutableLiveData(true)

    val channelList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getChannelList {
            value = it
        }
    }
    val goodsTypeList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("货物", "C"),
            KeyValue("邮件", "M"),
            KeyValue("空板箱", "X"),
        )
    )

    val print = MutableLiveData(false)

    val diBangModel = DiBangWeightModel()

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    fun initOnCreated(activity: Activity, intent: Intent) {
        val car = intent.getStringExtra(Constant.Key.FLATCAR) ?: ""
        pageType.value = if (car.isEmpty()) DetailsPageType.Add else DetailsPageType.Modify
        dataBean.value?.carId = car

        diBangModel.weight.observe(activity as LifecycleOwner) {
            dataBean.value?.weighbridgeWeight = it
        }

        channel.observe(activity as LifecycleOwner) {
            diBangModel.key = it
        }

        getDetails()
    }

    fun getDetails() {
        if (dataBean.value?.carId.isNullOrEmpty()) return

        launchLoadingCollect({
            NetApply.api.getGncFuBangDetailsByCar(dataBean.value!!.carId)
        }) {
            onSuccess = {
                it.data?.let { bean ->
                    dataBean.value = bean
                    if (diBangModel.weight.value !== "") {
                        dataBean.value?.weighbridgeWeight = diBangModel.weight.value.toString()
                    }
                }
            }
        }
    }

    fun carScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.CAR)
    }

    fun uldScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.ULD)
    }

    fun onWeightLongClick(): Boolean {
        showWeightEdit.value = true
        return true
    }

    fun getUldInfo() {
        if (dataBean.value!!.uld.isEmpty()) {
            return
        }
        launchCollect({
            NetApply.api.getUldDetails(dataBean.value!!.uld)
        }) {
            onSuccess = {
                it.data?.let { data ->
                    dataBean.value?.uldWeight = data.uldWeight
                }
            }
            onFailed = { _, message ->
                showToast(message)
                dataBean.value?.uldWeight = ""
            }
        }
    }

    /**
     * 确认点击
     */
    fun confirmClick() {
        if (!verifyData()) {
            return
        }
        if (print.value!! && !BluetoothAdapter.getDefaultAdapter().isEnabled) {
            showToast("请打开设备蓝牙")
            return
        }
        val bean = dataBean.value!!
        launchLoadingCollect({
            NetApply.api.anyPost("DomExpWeighting/completed", bean.toRequestBody(true))
        }) {
            onSuccess = {
                showToast(it.msg.noNull("复磅成功"))

                if (print.value == true) {
                    BluetoothDialogModel()
                        .showCallBack {
                            bean.username = SharedPreferenceUtil.getString(Constant.Share.userName)
                            PrinterUtils.printFuBang(bean)
                        }
                }
                dataBean.value = GncFuBangBean()
            }
        }
    }

    private fun verifyData(): Boolean {
        val bean = dataBean.value!!
        if (bean.carId.isEmpty()) {
            showToast("请输入正确的平板车号")
            return false
        }
        if ((bean.carWeight.verifyNullOrEmpty("平板车信息未维护，设备不可用！")
                    || bean.pc.verifyNullOrEmpty("请输入件数")
                    || bean.volume.verifyNullOrEmpty("请输入体积"))
        ) {
            return false
        }

        val netWeight = bean.netWeight.toFloatOrNull() ?: 0f
        val currentWeight = bean.currentWeight.toFloatOrNull() ?: 0f
        if (abs((netWeight - currentWeight)) / abs(netWeight) > 0.03f) {
            showToast("平板车（${dataBean.value?.carId.noNull()}）复磅重量（${currentWeight}）较入库重量（${netWeight}）偏差超过3%，不允许复磅")
            return false
        }

        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.CAR -> {
                    dataBean.value!!.carId =
                        data.getStringExtra(Constant.Result.CODED_CONTENT) ?: ""
                    getDetails()
                }

                Constant.RequestCode.ULD -> {
                    dataBean.value!!.uld = data.getStringExtra(Constant.Result.CODED_CONTENT) ?: ""
                    getUldInfo()
                }
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        diBangModel.cancelLooperGet()
    }
}