package com.lukouguoji.gjj.viewModel

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.holder.GjjGoodsAddViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjjTallyRecordBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.interfaces.ICheck
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.finish
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.getActivity
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.limit
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.lukouguoji.module_base.util.CheckUtil
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue
import java.util.Calendar
import java.util.Date

class GjjGoodsAddViewModel : BasePageViewModel() {

    // 航班日期
    val flightDate = MutableLiveData(Date().formatDate())

    // 航班号
    val flightNo = MutableLiveData<String>()

    // 代理
    val agent = MutableLiveData<String>()

    // 运单号
    val waybillNo = MutableLiveData<String>()

    // 代理列表
    val agentList = MutableLiveData(emptyList<KeyValue>())

    val itemLayoutId = R.layout.item_gjj_goods_add
    val itemViewHolder = GjjGoodsAddViewHolder::class.java

    // 描述
    val desc = MutableLiveData("")

    init {
        DictUtils.getAgentList {
            agentList.postValue(it)
        }
    }

    override fun getData() {
        launchCollect({
            NetApply.api
                .getGjjGoodsTallyRecordList(
                    mapOf(
                        "fdate" to flightDate.value,
                        "fno" to flightNo.value,
                        "agent" to agent.value,
                        "wbNo" to waybillNo.value,
                    ).toRequestBody()
                )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    pageModel.handleDataList(it.data)
                    generateDesc()
                } else {
                    showToast(it.msg.noNull("获取数据失败"))
                }
            }
        }
    }

    /**
     * 条目点击事件
     */
    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as GjjTallyRecordBean
        when (type) {
            // 图标选中状态
            R.id.iv_icon -> {
                bean.checked.set(!bean.checked.get())
                generateDesc()
            }

            else -> {
                showToast("未知点击类型")
            }
        }
    }

    /**
     * 航班日期点击
     */
    fun onFlightDateClick(view: View) {
        Common.onYearMonthDay(
            view.context.getActivity(),
            flightDate.value!!
        ) { year, month, day ->
            val calendar = Calendar.getInstance()
            calendar.set(year, month - 1, day)
            flightDate.value = calendar.time.formatDate()
        }
    }

    /**
     * 代理点击
     */
    fun onAgentSelected(position: Int) {
        agent.value = agentList.value!![position].value
    }

    /**
     * 运单号扫描点击
     */
    fun onWaybillNoScanClick(view: View) {
        ScanModel.startScan(view.context.getActivity(), Constant.RequestCode.WAYBILL)
    }

    /**
     * 全选点击
     */
    fun onAllClick(view: View) {
        pageModel.rv?.commonAdapter()?.items?.let {
            CheckUtil.handleAllCheck(it as List<ICheck>)
            generateDesc()
        }
    }

    /**
     * 搜索点击
     */
    fun onSearchClick(view: View) {
        refresh()
    }

    /**
     * 确认点击
     */
    fun onConfirmClick(view: View) {
        val checkedList = getCheckedList()
        if (checkedList.isEmpty()) {
            showToast("请选择需要交接的数据")
            return
        }
        checkedList.count { it.agent == checkedList.first().agent }.let {
            if (it != checkedList.size) {
                showToast("请选择同一代理的数据")
                return
            }
        }
        showLoading()
        launchCollect({
            NetApply.api.gjjGoodsInsert(
                mapOf(
                    "agent" to checkedList.first().agent,
                    "pc" to checkedList.sumOf { it.pc ?: 0 },
                    "weight" to checkedList.sumOf { it.weight.noNull("0.0").toDouble() }.limit(),
                    "whidList" to checkedList.map { it.whid }
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("交接成功"))
                    view.context.finish()
                } else {
                    showToast(it.msg.noNull("交接失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 生成描述
     */
    fun generateDesc() {
        val checkedList = getCheckedList()
        if (checkedList.isEmpty()) {
            desc.value = "合计：0票，件数：0，重量：0KG"
        }
        val count = checkedList.size
        val weight = checkedList.sumOf { it.weight?.toDouble() ?: 0.0 }
        val pc = checkedList.sumOf { it.pc ?: 0 }
        desc.value = "合计：${count}票，件数：${pc}，重量：${weight.limit(2)}KG"
    }

    /**
     * 获取选中的列表
     */
    private fun getCheckedList(): List<GjjTallyRecordBean> {
        return (pageModel.rv?.commonAdapter()?.items?.filter {
            it is GjjTallyRecordBean && it.checked.get()
        } ?: emptyList()) as List<GjjTallyRecordBean>
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.WAYBILL -> {
                    val id = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                    waybillNo.value = id
                }

                else -> {}
            }
        }
    }
}