package com.sixin.module_p.ui.goods.transport.list

import android.app.Activity
import android.content.Intent
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GoodsTransportBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
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.loge
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.model.GoodsTransportModifyDialogModel
import com.lukouguoji.module_base.model.GoodsTransportReturnDialogModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.HandlerUtils
import com.sixin.module_p.R
import com.sixin.module_p.ui.goods.transport.dialog.PdaGoodsTransportFilterDialogModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class PdaGoodsTransportListViewModel : BasePageViewModel() {
    // 平板车
    val keyWord = MutableLiveData("")

    // 数量
    val count = MutableLiveData(0)

    val index = MutableLiveData(0)

    val itemLayoutId = R.layout.item_pda_zhuanyun_list
    val itemViewHolder = PdaGoodsTransportListViewHolder::class.java

    // 筛选
    private val filterModel = PdaGoodsTransportFilterDialogModel {
        refresh()
    }

    // 补位补充是否可用
    val supplementEnable = MutableLiveData(false)

    // 确认按钮是否可用
    val confirmEnable = MutableLiveData(true)

    // 退回按钮是否可用
    val returnEnable = MutableLiveData(false)

    // 确认文字
    val confirmText = MutableLiveData("开始运输")

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


    /**
     * tab切换
     */
    fun onTabChanged(index: Int) {
        this.index.value = index
        refresh()
    }



    fun initOnCreated() {
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                keyWord.value = it
//                onCarChange()
                findMatchInputCarNo(it)
            }.launchIn(viewModelScope)
    }

    override fun getData() {
        launchLoadingCollect({
            NetApply.api.getGoodsTransportList(
                mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "fdate" to filterModel.date.value,
                    "fno" to filterModel.flightNo.value,
                    "transStatus" to index.value,
                    "transType" to filterModel.transportType.value,
                    "driver" to filterModel.driver.value,
                    "carId" to keyWord.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                it.list?.forEach { iit -> iit.storageAreaVisible = index.value == 0}
                pageModel.handleListBean(it)
                count.value = it.total
                HandlerUtils.postRunnable({
                    computeEnableState()
                }, 100)
            }
        }
    }

    fun findMatchInputCarNo(carNo: String){
        Log.i("TEST","findMatchInputCarNo  $carNo")
        if(carNo.length>=3){
            val list = pageModel.rv?.commonAdapter()?.items as? List<GoodsTransportBean> ?: return
            Log.i("TEST","findMatchInputCarNo  ${list.size}")
            for(i in list.indices){
                list[i].carId.let {
                    if(it.contains(carNo)){
                        Log.i("TEST","findMatchInputCarNo  $i")
                        pageModel.rv?.smoothScrollToPosition(i)
                        if(!list[i].checked.get()){
                            list[i].checked.set(true)
                            pageModel.rv?.commonAdapter()?.notifyItemChanged(i)
                        }
                        return
                    }
                }
            }
        }
    }


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

    fun onFilterClick() {
        filterModel.show()
    }

    fun returnClick() {
        val list = (getAdapter().items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选择数据")
            return
        }
        val inOutStatus = list.first().status
        GoodsTransportReturnDialogModel(
            list.joinToString("、") { it.carId }
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = if (inOutStatus == "0") "DomExpLoading/backTrans" else "unloadingAirCraft/backTrans",
                    mapOf(
                        "backDirection" to it.data.value,
                        "transType" to list.first().transType,
                        "useIdList" to list.map { it.useId }
                    ).toRequestBody())
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("退回成功"))
                    refresh()
                }
            }
        }.show()
    }

    fun onAddCargo() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = (adapter.items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要加货的平板车信息!")
            return
        }
        getTopActivity().showConfirmDialog("是否完成加货?") {
            var canAddCargo = true
            for (obj in list) {
                if (obj.addCargoFlag != "1") {
                    showToast("平板车不可加货!")
                    canAddCargo = false
                    break
                }
            }
            if (canAddCargo) {
                launchLoadingCollect({
                    NetApply.api.anyPost(
                        url = "DomExpLoading/updateAddCargo",
                        mapOf(
                            "useIdList" to list.map { it.useId },
                        ).toRequestBody()
                    )
                }) {
                    onSuccess = {
                        showToast(it.msg.noNull("完成加货成功"))
                        refresh()
                    }
                }
            }
        }


    }

    fun onSupplementClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = (adapter.items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要补充机位的平板车信息!")
            return
        }
        val inOutStatus = list.first().status
        GoodsTransportModifyDialogModel(
            list.joinToString("、") { it.carId }
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = "DomExpLoading/updateStandId",
                    mapOf(
                        "status" to inOutStatus,
                        "standId" to it.data.value,
                        "transType" to list.first().transType,
                        "useIdList" to list.map { it.useId },
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("补充机位成功"))
                    refresh()
                }
            }
        }.show()
    }

    fun onConfirmClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = (adapter.items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要转运的平板车信息!")
            return
        }
        val inOutStatus = list.first().status
        getTopActivity().showConfirmDialog("是否确定${confirmText.value}？") {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = if (inOutStatus == "0") {
                        if (confirmText.value == "开始运输") "DomExpLoading/startTrans" else "DomExpLoading/finishTrans"
                    } else {
                        if (confirmText.value == "开始运输") "unloadingAirCraft/startTrans" else "unloadingAirCraft/finishTrans"
                    },
                    mapOf(
                        "transType" to list.first().transType,
                        "useIdList" to list.map { it.useId }
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("操作成功"))
                    refresh()
                }
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val list = getAdapter().items as List<GoodsTransportBean>
        val bean = list[position]
        if (!bean.canReturn() && bean.endFlag == "1") {
            // 不能退回且已结束的数据不允许点击
            return
        }
        when (type) {
            R.id.ll -> {
                val checkedStatus = list.firstOrNull { it.checked.get() }?.transStatus ?: ""
                // 没有选中,或选中状态一致,则处理逻辑
                if (checkedStatus.isEmpty() || checkedStatus == bean.transStatus) {
                    bean.checked.set(!bean.checked.get())
                }
            }

            else -> {}
        }
        computeEnableState()
    }

    /**
     * 计算可用信息
     */
    private fun computeEnableState() {
        val list = getAdapter().items as List<GoodsTransportBean>
        // 补充机位是否可用
//        supplementEnable.value = list.firstOrNull()?.transType in listOf("2", "8", "9")

        // 选中结束状态的数据,则不展示
        confirmEnable.value = list.firstOrNull { it.checked.get() }?.endFlag != "1"
        if (index.value == 2) {
            //完成运输页面不可以开始运输
            confirmEnable.value = false
        }
        // 确认是否可用
        confirmText.value = if (list.firstOrNull { it.checked.get() }?.transStatus == "1") {
            "完成运输"
        } else {
            "开始运输"
        }
       if (index.value == 1) {
           confirmText.value = "完成运输"
       }
        val userRole = SharedPreferenceUtil.getString(Constant.Share.roleId).noNull()
        supplementEnable.value = userRole == "7" && !confirmEnable.value!!
        loge("判断补充机位是否可用 : ${supplementEnable.value}")

        // 退回是否可用
        returnEnable.value = list.firstOrNull { it.checked.get() }?.canReturn() == true
    }

    private fun getAdapter() = pageModel.rv!!.commonAdapter()!!

    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 -> {
                val carNo = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                keyWord.value = carNo
//                onCarChange()
                findMatchInputCarNo(carNo)
            }

            else -> {}
        }
    }

}