package com.lukouguoji.gnc.page.stash.list

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.page.stash.details.GncStashDetailsActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GncStashBean
import com.lukouguoji.module_base.bean.SimpleCheckBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.formatDate
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.PadFilterDialogModel
import com.lukouguoji.module_base.model.PadFilterModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.Common
import dev.DevUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import okhttp3.RequestBody

class GncStashListViewModel : BasePageViewModel() {

    // 日期
    val date = MutableLiveData(DateUtils.getCurrentTime().formatDate())
    val dateEnd = MutableLiveData("")

    val fNo = MutableLiveData("")
    val dest = MutableLiveData("")

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

    // 运单号列表
    val wbNoList = MutableLiveData<List<String>>()

    // 排列方式
    val sortType = MutableLiveData("0")
    val sortTypeList = MutableLiveData(
        listOf(
            KeyValue("入库时间", "0"),
            KeyValue("航程", "1"),
            KeyValue("库位", "2"),
        )
    )

    // 上舱状态
    val status = MutableLiveData("")
    val statusList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("未上舱", "0"),
            KeyValue("已上舱", "1"),
        )
    )

    val itemLayoutId = R.layout.item_gnc_stash_list
    val itemViewHolder = GncStashListViewHolder::class.java

    private val filterDialogModel: PadFilterDialogModel by lazy {
        PadFilterDialogModel(
            DevUtils.getTopActivity(), listOf(
                PadFilterModel(
                    data = fNo,
                    title = "航班号",
                    hint = "请输入航班号",
                    forcedCap = true
                ),
                PadFilterModel(
                    data = dest,
                    title = "目的港",
                    hint = "请输入目的港",
                    forcedCap = true
                ),
            )
        ) {
            refresh()
        }
    }

    val countDesc = MutableLiveData("合计：0条，总件数：0，总重量：0KG")

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

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

    fun onFilterClick() {
        filterDialogModel.show()
    }

    fun getWayBillList() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "beginDate" to date.value,
            "endDate" to dateEnd.value,
            "locStatus" to status.value,
            "wbNo" to waybill.value,
            "fno" to fNo.value,
            "dest" to dest.value,
        ).toRequestBody()
        launchCollect({
            NetApply.api.getWbNoList(
                "/DomExpWareHouse/searchWbList",
                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()
            }
        }
    }

    override fun getData() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "beginDate" to date.value,
            "endDate" to dateEnd.value,
            "orderBy" to sortType.value,
            "locStatus" to status.value,
            "wbNo" to waybill.value,
            "fno" to fNo.value,
            "dest" to dest.value,
        ).toRequestBody()
        launchLoadingCollect({
            NetApply.api.getGncStashList(requestBody)
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                getCountData(requestBody)
            }
        }
    }

    private fun getCountData(requestBody: RequestBody) {
        launchCollect({
            NetApply.api.simplePost("DomExpWareHouse/total", requestBody)
        }) {
            onSuccess = {
                countDesc.value =
                    "合计：${it.data?.total}条，总件数：${it.data?.pc}，总重量：${it.data?.weight}KG"
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        println("onItemClick...")
        val bean = pageModel.rv!!.commonAdapter()!!.getItem(position) as GncStashBean
        GncStashDetailsActivity.start(getTopActivity(), bean.whId)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.WAYBILL -> {
                    val id = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                    waybill.value = id
                }
            }
        }
    }
    private 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!![position]
        }
    }


}