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

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gnc.page.stash.details.GncPdaStashDetailsActivity
import com.lukouguoji.module_base.base.BasePageViewModel
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.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.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.model.BluetoothDialogModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.PrinterUtils
import com.sixin.module_p.R
import com.sixin.module_p.ui.gnc.shouyun.dialog.GncPdaShouYunSyncDialogModel
import com.sixin.module_p.ui.gnc.shouyun.dialog.PdaShouYunFilterDialogModel
import com.sixin.module_p.ui.gnc.shouyun.un.list.GncUnShouYunViewHolder
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class GncShouYunViewModel : BasePageViewModel() {

    // 平板车
    val keyWord = MutableLiveData("")

    // 数量
    val count = MutableLiveData(0)

    val itemLayoutId = R.layout.item_shou_yun_list
    val itemViewHolder = GncShouYunViewHolder::class.java

    // 筛选
    private val filterModel = PdaShouYunFilterDialogModel({
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.WAYBILL)
    }) {
        refresh()
    }



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

    init {
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                if (it.length == 11) {
                    filterModel.waybill.value = it
                    refresh()
                } else {
                    keyWord.value = it
                    onCarChange(false)
                }
            }
            .launchIn(viewModelScope)
    }

    override fun getData() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "location" to keyWord.value,
            "fdate" to filterModel.date.value,
            "opDate" to filterModel.dateRuKu.value,
            "fno" to filterModel.flightNo.value,
            "wbNo" to filterModel.waybill.value,
        ).toRequestBody()
        launchLoadingCollect({
            NetApply.api.getGncShouYunList(requestBody)
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total
            }
        }
    }

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

    override fun onItemClick(position: Int, type: Int) {
        println("国内出港收运记录 onItemClick...")
        when (type) {
            R.id.shouyunItem -> {
                // TODO: item点击
                println("国内出港收运记录 onItemClick...")
                val bean = pageModel.rv!!.commonAdapter()!!.getItem(position) as GncShouYunBean
                GncPdaStashDetailsActivity.start(getTopActivity(), bean.whId)
            }

            else -> {}
        }
    }

    fun onFilterClick() {
        filterModel.show()
    }

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (data == null || resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            Constant.RequestCode.CAR -> {
                keyWord.value = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                refresh()
            }

            Constant.RequestCode.WAYBILL -> {
                filterModel.waybill.value =
                    data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                refresh()
            }

            else -> {}
        }
    }


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

    /**
     * 展示重新同步
     */
    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) }
                GncPdaShouYunSyncDialogModel(no, list1) { model ->
                    println(model.list)
                    launchLoadingCollect({
                        NetApply.api.anyPost(
                            "DomExpCheckIn/reUpdateAgt",
                            mapOf(
                                "list" to model.list
                            ).toRequestBody()
                        )
                    }) {
                        onSuccess = { b ->
                            showToast(b.msg.noNull("重新同步成功"))
                        }
                    }
                }.show()
            }
        }
    }



}