package com.lukouguoji.gnc.page.shouyun.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.query.details.GncQueryDetailsActivity
import com.lukouguoji.gnc.page.shouyun.details.dialog.GncShouYunSyncDialogModel
import com.lukouguoji.gnc.page.stash.details.GncStashDetailsActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GncShouYunBean
import com.lukouguoji.module_base.bean.GncStashBean
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.showToast
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.BluetoothDialogModel
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.ui.weight.search.layout.SearchLayoutType
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import com.lukouguoji.module_base.util.PrinterUtils
import dev.DevUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import okhttp3.RequestBody
import java.util.Collections.emptyList

class GncShouYunListViewModel : BasePageViewModel() {

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

    // 目的港
    val dest = MutableLiveData("")
    val waybill = MutableLiveData("")

    // 代理
    val agentList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getGncAgentList() {
            value = it
        }
    }
    var agent = MutableLiveData("")

    // 特码
    val spCodeList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getSpecialCodeList(parentcode = "ALL") {
            value = it
        }
    }
    var spCode = MutableLiveData("")

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

    // 数量
    val count = MutableLiveData("0")
    val number = MutableLiveData("0")
    val weight = MutableLiveData("0")

    val itemLayoutId = R.layout.item_gnc_shouyun
    val itemViewHolder = GncShouYunListViewHolder::class.java

    private val filterModel by lazy {
        PadFilterDialogModel(
            getTopActivity(), listOf(
                PadFilterModel(spCode, "特码", "请选择特码", SearchLayoutType.SPINNER, spCodeList),
                PadFilterModel(
                    dest,
                    "目的港",
                    "请输入目的港",
                    SearchLayoutType.INPUT,
                    forcedCap = true
                ),
            )
        ) {
            refresh()
        }
    }

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

    fun getWayBillList() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "opDate" to date.value,
            "agentCode" to agent.value,
            "spCode" to spCode.value,
            "wbNo" to waybill.value,
            "dest" to dest.value,
            "fdate" to fdate.value,
            "fno" to fno.value,
        ).toRequestBody()
        launchCollect({
            NetApply.api.getGncShouYunWbNoList(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 = { _: Int, _: String ->
                wbNoList.value = emptyList()
            }
        }
    }

    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]
        }
    }


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

    private fun getCountData(requestBody: RequestBody) {
        launchCollect({
            NetApply.api.simplePost("DomExpCheckIn/total", requestBody)
        }) {
            onSuccess = {
                number.value = it.data?.pc ?: "0"
                weight.value = it.data?.weight ?: "0"
            }
        }
    }

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

    fun filterClick(){
        filterModel.show()
    }

    /**
     *  点击
     */
    fun onConfirmClick() {
        val list = (pageModel.rv?.commonAdapter()?.items?.filter {
            (it as GncShouYunBean).checked.get()
        } ?: emptyList()) as List<GncShouYunBean>
        if (list.isEmpty()) {
            showToast("请选择需要打印的数据")
            return
        }
        BluetoothDialogModel()
            .showCallBack {
                list.forEach {
                    PrinterUtils.printShouYun(it)
                }
            }
    }

    override fun onItemClick(position: Int, type: Int) {
        println("GNCShouYunListViewModel国内出港收运记录 onItemClick...")
        val bean = pageModel.rv!!.commonAdapter()!!.getItem(position) as GncShouYunBean
        GncStashDetailsActivity.start(getTopActivity(), bean.whId)
    }

    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 -> {
                    waybill.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                }

                else -> {}
            }
        }
    }

    /**
     * 展示重新同步
     */
    fun showSyncDialog() {

        val list =
            (pageModel.rv!!.commonAdapter()!!.items as List<GncShouYunBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选择需要重新同步的数据")
            return
        }
        val no = list.get(0).wbNo

        for (obj in list){
            if (no != obj.wbNo){
                showToast("只能选择相同运单号的数据进行同步")
                return
            }
        }
        var loactionList = list.map { it.location }
        launchLoadingCollect({
            NetApply.api.getShouYunSyncList(
                mapOf(
                    "wbNo" to no
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                val ShouYunSyncBeanlist = (it.data ?: emptyList())

                val list1 = ShouYunSyncBeanlist.filter { loactionList.contains(it.location) }
                GncShouYunSyncDialogModel(no, list1) { model ->
                    println(model.list)
                    launchLoadingCollect({
                        NetApply.api.anyPost(
                            "DomExpCheckIn/reUpdateAgt",
                            mapOf(
                                "list" to model.list
                            ).toRequestBody()
                        )
                    }) {
                        onSuccess = { b ->
                            showToast("重新同步成功")
                        }
                    }
                }.show()
            }
        }
    }

}