package com.lukouguoji.gnc.page.shouyun.details

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.observe
import com.lukouguoji.gnc.page.shouyun.details.dialog.GncShouYunSyncDialogModel
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GncShouYunBean
import com.lukouguoji.module_base.bean.ShouYunSyncBean
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.limit
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showConfirmDialog
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 okhttp3.RequestBody
import kotlin.math.abs
import kotlin.math.roundToInt

class GncShouYunDetailsViewModel : BaseViewModel() {

    val pageType = MutableLiveData(DetailsPageType.Add)

    val channel = MutableLiveData("")

    val dataBean = MutableLiveData(GncShouYunBean())

    val showWeightEdit = MutableLiveData(false)

    val channelList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getChannelList {
            value = it
        }
    }
    val agentList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getGncAgentList(addAll = false) {
            value = listOf(KeyValue("", "")) + it
        }
    }
    val spCodeList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getSpecialCodeList(addAll = false, parentcode = "ALL") {
            value = listOf(KeyValue("", "")) + it
        }
    }
    val wxKuList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getWxKuList {
            value = listOf(KeyValue("", "")) + it
        }
    }
    val wxDescList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getWxDescListValue {
            value = listOf(KeyValue("", "")) + it
        }
    }

    val packageTypeList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getShouYunPackageTypeList {
            value = listOf(KeyValue("", "")) + it
        }
    }

    val print = MutableLiveData(true)


    val diBangModel = DiBangWeightModel()
    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    fun initOnCreated(intent: Intent) {
        dataBean.value!!.wbNo = intent.getStringExtra(Constant.Key.WAYBILL) ?: ""
        pageType.value =
            if (dataBean.value!!.wbNo.isEmpty()) DetailsPageType.Add else DetailsPageType.Modify

        getDetails()

        // 监听重量改变
        diBangModel.weight.observe(getTopActivity() as LifecycleOwner) {
            if (it.isNotEmpty()) {
                dataBean.value?.weight = it
            }
        }

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

    fun getDetails() {
        val waybill = dataBean.value!!.wbNo
        if (dataBean.value!!.wbNo.isEmpty() || dataBean.value!!.wbNo.length != 11) return
        launchLoadingCollect({
            NetApply.api.getGncShouYunDetails(waybill)
        }) {
            onSuccess = {
                it.data?.let { bean ->
                    bean.weight = ""
                    bean.pc = ""
                    bean.volume = ""
                    dataBean.value = bean
                }
            }
        }
    }

    fun waybillScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.WAYBILL)
    }

    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 getCarInfo() {
        if (dataBean.value!!.carNo.isEmpty()) {
            return
        }
        launchCollect({
            NetApply.api.getCarDetails(dataBean.value!!.carNo)
        }) {
            onSuccess = {
                dataBean.value?.carWeight = it.data?.carWeight ?: ""
            }

            onFailed = { _, message ->
                showToast(message)
                dataBean.value?.carWeight = ""
            }
        }
    }

    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 printClick() {
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled) {
            showToast("请打开设备蓝牙")
            return
        }
        printShouYun(dataBean.value!!, false)
    }

    /**
     * 校验点击
     */
    fun verifyClick() {
        if (dataBean.value!!.carWeight.isEmpty()) {
            showToast("平板车信息未维护，设备不可用！")
            return
        }
        val wFloat = dataBean.value?.weight.orEmpty().toFloatOrNull() ?: 0f
        val carFloat = dataBean.value?.carWeight.orEmpty().toFloatOrNull() ?: 0f
        if (abs(wFloat - carFloat) > (carFloat * 0.03)) {
            getTopActivity().showConfirmDialog("误差超过3%，是否覆盖？") {
                launchLoadingCollect({
                    NetApply.api.simplePost(
                        "/eqm/flatcar/updateFlatcar", mapOf(
                            "carId" to dataBean.value!!.carNo,
                            "carWeight" to wFloat.roundToInt(),
                        ).toRequestBody()
                    )
                }) {
                    onSuccess = {
                        getCarInfo()
                    }
                }
            }
        } else {
            showToast("数据在误差范围内")
        }
    }

    /**
     * 分斗点击
     */
    fun apartClick() {
        if (!verifyData()) {
            return
        }
        launchLoadingCollect({
            NetApply.api.anyPost("DomExpCheckIn/divided", dataBean.value!!.toRequestBody(true))
        }) {
            onSuccess = {
                showToast(it.msg.noNull("分斗成功"))
                dataBean.value?.carNo  = ""
                dataBean.value?.pc = ""
                dataBean.value?.weight = ""
                dataBean.value?.volume = ""
            }
        }
    }

    /**
     * 确认点击
     */
    fun confirmClick() {
        if (!verifyData()) {
            return
        }
        showSyncDialog(dataBean.value!!.wbNo)
    }


    private fun showSyncDialog(waybill: String) {
        val data = dataBean.value!!
        launchLoadingCollect({
            NetApply.api.getShouYunSyncList(
                mapOf(
                    "wbNo" to waybill
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                //相同板车号收运需要叠加
                var isAdd = true
                var dbPc = 0
                var dbWeight = 0.0
                var dbVolume = 0.0
                if (!data.carNo.isNullOrEmpty()){
                    it.data?.forEach { t ->
                        if (t.location.equals(data.carNo)){
                            println("匹配到对应平板车，件数重量累加")
                            isAdd = false
                            dbPc = t.pc.toInt()
                            dbWeight = t.weight.toDouble()
                            dbVolume = t.volume.toDouble()
                            t.pc = ((t.pc.toInt()).plus(data.pc.toInt())).toString()
                            t.weight = ((t.weight.toDouble()).plus(data.weight.toDouble())).toString()
                            t.volume = (t.volume.toDouble().plus(data.volume.toDouble())).toString()
                        }

                    }
                }
                var list = (it.data ?: emptyList())
                if (isAdd){
                    list = (it.data ?: emptyList()) + listOf(
                        ShouYunSyncBean().apply {
                            location = data.carNo
                            pc = data.pc
                            weight = data.weight
                            volume = data.volume
                        }
                    )
                }
                GncShouYunSyncDialogModel(waybill, list) { model ->
                    if (isAdd){
                        val last = list.last()
                        data.pc = last.pc
                        data.weight = last.weight
                        data.volume = last.volume
                        list = list.subList(0, list.size - 1)
                    }else{
                        list.forEach {t ->
                            if (t.location.equals(data.carNo)) {
                                val pc = (t.pc.toInt()).minus(dbPc)
                                val weight = (t.weight.toDouble()).minus(dbWeight)
                                if (pc <= 0){
                                    showToast("本次收运件数少于等于0！")
                                    return@GncShouYunSyncDialogModel
                                }
                                if (weight <= 0){
                                    showToast("本次收运重量少于等于0！")
                                    return@GncShouYunSyncDialogModel
                                }
                                data.pc = pc.toString()
                                data.weight = weight.toString()
                                data.volume =  (weight / 220f).limit(2)
                                t.pc =dbPc.toString()
                                t.weight=dbWeight.toString()
                                t.volume = dbVolume.toString()
                            }
                        }
                    }
                    launchLoadingCollect({
                        NetApply.api.anyPost(
                            "DomExpCheckIn/updateWarehouseList",
                            mapOf(
                                "list" to list,
                                "wb" to data
                            ).toRequestBody()
                        )
                    }) {
                        onSuccess = { b ->
                            showToast(b.msg.noNull("同步成功"))
                            println("------------onSuccess")
                            dataBean.value = GncShouYunBean()
                        }

                    }
                }.show()
            }
        }
    }

    /**
     * 打印挂签
     */
    private fun printShouYun(bean: GncShouYunBean, showSync: Boolean) {
        bean.location = bean.carNo
        bean.username = SharedPreferenceUtil.getString(Constant.Share.userName)
        BluetoothDialogModel()
            .showCallBack {
                PrinterUtils.printShouYun(bean)
                if (showSync) {
                    showSyncDialog(bean.wbNo)
                }
            }
    }

    private fun verifyData(): Boolean {
        val bean = dataBean.value!!
        if (bean.wbNo.length != 11 || bean.mawbId.isEmpty()) {
            showToast("请输入正确的运单号")
            return false
        }
        if (bean.pc.verifyNullOrEmpty("请输入件数")
            || bean.agentCode.verifyNullOrEmpty("请选择代理人")
            || bean.spCode.verifyNullOrEmpty("请选择特码")
            || bean.weight.verifyNullOrEmpty("请输入重量")
            || bean.volume.verifyNullOrEmpty("请输入体积")
        ) {
            return false
        }
        //●如果特码=DGR,则危险品库不能为空！
        if (bean.spCode.equals("DGR")){
            if (bean.dgrLocation.verifyNullOrEmpty("特码为DGR,危险品库不能为空！")){
                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.WAYBILL -> {
                    dataBean.value!!.wbNo = data.getStringExtra(Constant.Result.CODED_CONTENT) ?: ""
                    getDetails()
                }

                Constant.RequestCode.CAR -> {
                    dataBean.value!!.carNo =
                        data.getStringExtra(Constant.Result.CODED_CONTENT) ?: ""
                    getCarInfo()
                }

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

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

