package com.sixin.module_p.ui.gnc.shouyun.un.list

import android.app.Activity
import android.content.Intent
import android.util.Log
import android.widget.ArrayAdapter
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GncShouYunBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.Common
import com.sixin.module_p.R
import com.sixin.module_p.ui.gnc.shouyun.add.PdaShouYunAddActivity
import com.sixin.module_p.ui.gnc.shouyun.dialog.PdaDaiShouYunFilterDialogModel
import com.sixin.module_p.ui.gnc.shouyun.list.PdaGncShouYunActivity
import dev.DevUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class GncUnShouYunViewModel : BasePageViewModel() {

    // 运单号
    val waybill = MutableLiveData("")

    // 数量
    val count = MutableLiveData(0)

    val itemLayoutId = R.layout.item_un_shou_yun_list
    val itemViewHolder = GncUnShouYunViewHolder::class.java

    val wbNoList = MutableLiveData<List<String>>()

    private val filterModel = PdaDaiShouYunFilterDialogModel {
        getData()
    }

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

    init {
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                waybill.value = it
                onWaybillChange(focused = false)
            }
            .launchIn(viewModelScope)
    }
    fun getWayBillList(input : String) {
        val requestBody = mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit,
            "fdate" to filterModel.date.value,
            "fno" to filterModel.flightNo.value,
            "agentCode" to filterModel.agent.value,
            "spCode" to filterModel.spCode.value,
            "dest" to filterModel.dest.value,
            "wbNo" to input
        ).toRequestBody()
        launchCollect({
            NetApply.api.getGncShouYunUnWbNoList(
                requestBody
            )
        }) {
            onSuccess = {
                val results = it.data!!
                when {
                    results.size == 1 -> {
                        waybill.value = results[0]
                        wbNoList.value = emptyList()
                    }
                    results.size > 1 -> {
                        wbNoList.value = results
                        showWbNoListSelect()
                    }
                    else -> {
                        wbNoList.value = emptyList()
                    }
                }
            }
            onFailed = { i: Int, s: String ->
                wbNoList.value = emptyList()
            }
        }

    }

    fun showWbNoListSelect() {
        Common.singleSelect(
            DevUtils.getTopActivity(),
            "选择运单号",
            JSONArray.parseArray(wbNoList.value!!.map {
                mapOf(
                    "name" to it,
                    "code" to it,
                )
            }.toList().toJson(false)),
            null
        ) { position, _ ->
            waybill.value = wbNoList.value!!.get(position)
            onWaybillChange(false)
        }
    }

    override fun getData() {
        val requestBody = mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit,
            "fdate" to filterModel.date.value,
            "fno" to filterModel.flightNo.value,
            "agentCode" to filterModel.agent.value,
            "spCode" to filterModel.spCode.value,
            "wbNo" to waybill.value,
            "dest" to filterModel.dest.value,
        ).toRequestBody()
        launchLoadingCollect({
            NetApply.api.getGncShouYunUnList(
                requestBody
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total
            }
        }
    }

    fun onWaybillChange(focused: Boolean = false) {
        if (focused) {
            return
        }
        refresh()
    }

    override fun onItemClick(position: Int, type: Int) {
        loge("点击事件: $position  $type")
        val bean = pageModel.rv!!.commonAdapter()!!.getItem(position) as GncShouYunBean
        when (type) {
            R.id.ll_content -> {
                PdaShouYunAddActivity.start(DevUtils.getTopActivity(), bean.wbNo)
            }

            else -> {}
        }
    }

    fun onFilterClick() {
        filterModel.show()
    }

    fun onAddClick() {
        PdaShouYunAddActivity.start(DevUtils.getTopActivity())
    }

    fun onMenuClick() {
        PdaGncShouYunActivity.start(DevUtils.getTopActivity())
    }

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        loge(
            "扫码返回信息 : $resultCode ; ${data != null} ; ${
                data?.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
            }"
        )
        if (data == null || resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            Constant.RequestCode.WAYBILL -> {
                waybill.value = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                onWaybillChange(focused = false)
            }

            else -> {}
        }
    }
}