package com.sixin.module_p.ui.enter.gn.document

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.DocumentHandoverBean
import com.lukouguoji.module_base.bean.GncCunFangBean
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.launchCollect
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.ScanModel
import com.sixin.module_p.R
import com.sixin.module_p.ui.gnc.cunfang.list.PdaGncCunFangAddDialogModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class PDADocumentViewModel: BasePageViewModel() {

    val flightNumber = MutableLiveData("")

    val index = MutableLiveData(0)

    val count = MutableLiveData(0)

    val unSaveSelectedCount = MutableLiveData(0)

    val itemLayoutId = R.layout.item_pda_document_handover_list
    val itemViewHolder = PdaDocumentHandoverViewHolder::class.java

    private val filterModel = PdaDocumentHandoverFilterDialogModel{
        refresh()
    }

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

    fun initOnCreated(intent: Intent) {
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                flightNumber.value = it
                onFlightNumberChange()
            }.launchIn(viewModelScope)
    }

    override fun getData() {
        launchLoadingCollect({
            NetApply.api.getDocumentHandoverList(
                mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "fdate" to filterModel.date.value,
                    "fno" to flightNumber.value,
                    "fileType" to filterModel.docType.value,
                    "ieFlag" to filterModel.ieFlag.value,
                    "reviewStatus" to filterModel.reviewStatus.value
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total
            }
            onComplete = {
                pageModel.finishLoading()
            }
        }
    }


    /**
     * 筛选点击
     */
    fun onFilterClick() {
        filterModel.show()
    }

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

    private fun resetUnSaveSelectedCount(){
        unSaveSelectedCount.postValue(0)
    }
    private fun refreshPage(){
        resetUnSaveSelectedCount()
        refresh()
    }

    fun onReviewClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<DocumentHandoverBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        val reviewed = filter.filter { it.reviewer != "" }
        if (reviewed.isNotEmpty()) {
            showToast("存在已复核数据")
            return
        }
        // 判断选择的项中是否存在不是当前登录用户为交接司机的
        val currentUserName = SharedPreferenceUtil.getString(Constant.Share.userName).noNull()
        val notCurrentDriver = filter.filter { iit -> iit.driver != "" && iit.driver != currentUserName }
        if (notCurrentDriver.isNotEmpty()) {
            showToast("不可复核分配司机不是自己的数据")
            return
        }
        launchLoadingCollect({
            NetApply.api.anyPost(
                "flt/reviewHandover", mapOf(
                    "idList" to filter.map { b -> b.id },
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                showToast(it.msg.noNull("分配区域成功"))
                refreshPage()
            }
        }
    }

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

            else -> {}
        }
    }


    override fun onItemClick(position: Int, type: Int) {
        super.onItemClick(position, type)
        if(type == R.id.pda_handover_checkBox){
            val list = pageModel.rv!!.commonAdapter()!!.items as List<DocumentHandoverBean>
            val oldValue = unSaveSelectedCount.value
            if (oldValue != null) {
                if(list[position].checked.get()){
                    if(oldValue<list.size){
                        unSaveSelectedCount.postValue(oldValue+1)
                    }
                }else{
                    if(oldValue>0){
                        unSaveSelectedCount.postValue(oldValue-1)
                    }
                }
            }
        }
    }

}