package com.lukouguoji.gjj.viewModel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.activity.GjjManifestAddActivity
import com.lukouguoji.gjj.activity.GjjManifestDetailsActivity
import com.lukouguoji.gjj.holder.GjjManifestListViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlightBean
import com.lukouguoji.module_base.bean.GjjManifestBean
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.interfaces.IOnItemClickListener
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.getActivity
import com.lukouguoji.module_base.ktx.getLifecycleOwner
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.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.CheckUtil
import com.lukouguoji.module_base.util.Common
import dev.DevUtils
import dev.utils.app.info.KeyValue
import java.util.Calendar
import java.util.Date

class GjjManifestListViewModel : BasePageViewModel(), IOnItemClickListener {

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

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

    // 始发站
    var departure = MutableLiveData<String>()

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

    // 始发站
    val departureList = MutableLiveData<List<KeyValue>>(emptyList())

    // 航班信息
    val flightBean = MutableLiveData<FlightBean>()

    val itemId = R.layout.item_gjj_manifest
    val viewHolder = GjjManifestListViewHolder::class.java

    // 描述
    val desc = MutableLiveData("合计：0票，件数：0，重量：0KG")

    private var firstIn = true

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

    /**
     * 初始化
     */
    fun init(context: Context) {
        flightNo.observe(context.getLifecycleOwner()) {
            getDepartureDictList()
        }
    }

    override fun getData() {
        if (!verifyHaveFlight()) {
            if (!firstIn)
                showToast("请输入正确航班信息")
            pageModel.finishLoading()
            firstIn = false
            return
        }
        launchCollect({
            NetApply.api
                .getGjjManifestList(
                    mapOf(
                        "fdate" to flightDate.value,
                        "fno" to flightNo.value,
                        "wbNo" to waybillNo.value,
                        "page" to pageModel.page,
                    ).toRequestBody()
                )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)

                val count = it.list?.size ?: 0
                val weight =
                    (it.list?.sumOf { b -> b.weight.noNull("0.0").toDouble() } ?: 0.0).limit()
                val pieces = it.list?.sumOf { b -> b.pc } ?: 0
                desc.value = "合计：${count}票，件数：${pieces}，重量：${weight}KG"
            }

            onComplete = {
                pageModel.finishLoading()
            }
        }
    }

    /**
     * 获取航班信息
     */
    private fun getDepartureDictList() {
        if (flightNo.value.isNullOrEmpty()) {
            return
        }
        launchCollect({
            NetApply.api
                .getGjFlightBean(
                    mapOf(
                        "fdate" to flightDate.value,
                        "fno" to flightNo.value,
                        "ieFlag" to "I",
                    ).toRequestBody()
                )
        }) {
            onSuccess = {
                if (it.verifySuccess() && it.data != null) {
                    flightBean.value = it.data
                    val list = mutableListOf(
                        KeyValue(it.data!!.fdep.noNull(), it.data!!.fdep.noNull()),
                    )
                    if (!it.data!!.jtz.isNullOrEmpty()) {
                        list.add(KeyValue(it.data!!.jtz.noNull(), it.data!!.jtz.noNull()))
                    }
                    departureList.value = list
                    refresh()
                } else {
                    flightBean.value = FlightBean()
                    departureList.value = emptyList()
                }
            }

            onFailed = { _, _ ->
                flightBean.value = FlightBean()
                departureList.value = emptyList()
            }
        }
    }

    /**
     * 航班日期 点击
     */
    fun flightDateClick(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()
            getDepartureDictList()
        }
    }

    /**
     * 始发站 点击
     */
    fun departureSelected(position: Int) {
        departure.value = departureList.value?.get(position)?.value
    }

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

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

    /**
     * 添加 点击
     */
    fun addClick(view: View) {
        if (flightBean.value?.fid.verifyNullOrEmpty("请先输入正确航班信息")) {
            return
        }
        GjjManifestAddActivity.start(
            view.context,
            flightBean.value?.fid?.toString() ?: "",
            flightBean.value?.fdep?.toString() ?: "",
            flightBean.value?.fdest?.toString() ?: "",
        )
    }

    /**
     * 删除 点击
     */
    fun deleteClick(view: View) {
        val list =
            pageModel.rv?.commonAdapter()?.items?.filter { (it as GjjManifestBean).checked.get() }
        if (list.isNullOrEmpty()) {
            showToast("请选择需要删除的数据")
            return
        }
        Common.secondConfirmDialog(
            view.context.getActivity(),
            "是否确认删除选中的${list.size}条数据?"
        ) { dialog ->
            dialog.dismiss()
            onDelete(list as List<GjjManifestBean>)
        }
    }

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

    /**
     * item 点击
     */
    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as GjjManifestBean
        when (type) {
            R.id.iv_icon -> {
                bean.checked.set(!bean.checked.get())
            }

            R.id.iv_show -> {
                CheckUtil.handleSingleCheck(adapter.items, "show", position)
            }

            R.id.tv_details -> {
                GjjManifestDetailsActivity.start(DevUtils.getTopActivity(), bean.mfId, bean.pic, bean.originalPic)
            }

            R.id.tv_delete -> {
                Common.secondConfirmDialog(
                    DevUtils.getTopActivity(),
                    "是否确认删除该条信息?"
                ) { dialog ->
                    dialog.dismiss()
                    onDelete(listOf(bean))
                }
            }

            else -> {}
        }
    }

    /**
     * 删除单条数据
     */
    private fun onDelete(list: List<GjjManifestBean>) {
        showLoading()
        launchCollect({
            NetApply.api.gjjManifestDeleteBatch(
                list.map { it.mfId }.toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("删除成功"))
                    refresh()
                } else {
                    showToast(it.msg.noNull("删除失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 校验是否有航班信息
     */
    private fun verifyHaveFlight() = !flightBean.value?.fid.isNullOrEmpty()

    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 -> {}
            }
        }
    }
}