package com.sixin.module_p.ui.gnc.cunfang.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.GncCunFangBean
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.interfaces.IOnItemClickListener
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.ScanModel
import com.sixin.module_p.R
import com.sixin.module_p.ui.gnc.cunfang.dialog.PdaCunFangFilterDialogModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class PdaGncCunFangListViewModel : BasePageViewModel(), IOnItemClickListener {

    val car = MutableLiveData("")

    val index = MutableLiveData(0)

    val count = MutableLiveData(0)

    val unSaveSelectedCount = MutableLiveData(0)

    val itemLayoutId = R.layout.item_pda_gnc_cunfang_list
    val itemViewHolder = PdaGncCunFangListViewHolder::class.java

    private val filterModel = PdaCunFangFilterDialogModel {
        refreshPage()
    }

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

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

    override fun getData() {
        resetUnSaveSelectedCount()
        launchLoadingCollect({
            NetApply.api.getGncCunFangList(
                mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "fdate" to filterModel.date.value,
                    "fno" to filterModel.flightNo.value,
                    "storageArea" to filterModel.area.value,
                    "copStatus" to filterModel.status.value,
                    "checkFlag" to filterModel.status.value,
                    "carId" to car.value,
                    "isStorage" to index.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total
            }
            onComplete = {
                pageModel.finishLoading()
            }
        }
    }

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

    fun refreshPage(){
        resetUnSaveSelectedCount()
        refresh()
    }

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

    fun onDistributionClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GncCunFangBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        val carList = filter.joinToString("、") { it.carId }
        PdaGncCunFangAddDialogModel(
            carList,
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    "DomExpLoading/allocationArea", mapOf(
                        "area" to it.area.value,
                        "useIdList" to filter.map { b -> b.useId },
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("分配区域成功"))
                    refreshPage()
                }
            }
        }.show(getTopActivity())
    }

    fun findMatchInputCarNo(carNo: String){
        if(carNo.length>=3){
            val list = pageModel.rv?.commonAdapter()?.items as? List<GncCunFangBean> ?: 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)
                            val oldValue = unSaveSelectedCount.value
                            if (oldValue != null) {
                                unSaveSelectedCount.postValue(oldValue+1)
                            }
                            pageModel.rv?.commonAdapter()?.notifyItemChanged(i)
                        }
                        return
                    }
                }
            }
        }
    }

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

            else -> {}
        }
    }

    private fun resetUnSaveSelectedCount(){
        unSaveSelectedCount.postValue(0)
    }
    override fun onItemClick(position: Int, type: Int) {
        super.onItemClick(position, type)
        if(type == R.id.pda_gnc_checkBox){
            val list = pageModel.rv!!.commonAdapter()!!.items as List<GncCunFangBean>
            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)
                    }
                }
            }
        }
    }

}