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.activity.GjjTallyDetailsActivity
import com.lukouguoji.gjj.activity.GjjTallyAddActivity
import com.lukouguoji.gjj.holder.GjjTallyListViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjjTallyBean
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.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.DevUtils
import dev.utils.app.info.KeyValue
import java.util.Calendar
import java.util.Date

class GjjTallyViewModel : BasePageViewModel() {

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

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

    // 代理
    private val agent = MutableLiveData("")

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

    // 理货状态
    private val tallyStatus = MutableLiveData("0")

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

    // 理货状态
    val tallyStatusList = DictUtils.tallyStatusList

    val itemId = R.layout.item_gjj_tally
    val itemHolder = GjjTallyListViewHolder::class.java

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

    init {
        // 获取代理列表
        DictUtils.getAgentList {
            agentList.postValue(it)
        }
    }

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

    /**
     * 条目点击事件
     */
    override fun onItemClick(position: Int, type: Int) {
        val bean = (pageModel.rv!!.commonAdapter()!!.getItem(position) ?: return) as GjjTallyBean
        when (type) {
            // 图标选中状态
            R.id.iv_icon -> {
                if (bean.canTally()) {
                    bean.checked.set(!bean.checked.get())
                }
            }
            // 详情
            R.id.tv_details -> {
                GjjTallyDetailsActivity.start(
                    DevUtils.getTopActivity(),
                    bean.mfId.noNull(),
                    bean.getWaybillNo()
                )
            }
            // 修改
            R.id.tv_modify -> {
                GjjTallyAddActivity.start(DevUtils.getTopActivity(), bean)
            }
            // 删除
            R.id.tv_delete -> {
                Common.secondConfirmDialog(
                    DevUtils.getTopActivity(),
                    "是否确认删除该条信息?"
                ) { dialog ->
                    dialog.dismiss()
                    onDeleteItem(bean)
                }
            }

            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?.get(position)?.value
    }

    /**
     * 理货状态 选中
     */
    fun onTallyStatusSelected(position: Int) {
        tallyStatus.value = tallyStatusList[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>)
        }
    }

    /**
     * 删除点击
     */
    fun onDeleteClick(view: View) {
        pageModel.rv?.commonAdapter()?.items?.let {
            val checkedList = (it as List<GjjTallyBean>)
                .filter { b -> b.checked.get() }
                .toList()
            if (checkedList.isEmpty()) {
                showToast("请选择要删除的条目")
            } else {
                showLoading()
                launchCollect({
                    NetApply.api.gjjTallyDeleteList(checkedList.map { it.mfId.noNull() }
                        .toRequestBody())
                }) {
                    onSuccess = {
                        if (it.verifySuccess()) {
                            showToast(it.msg.noNull("删除成功"))
                            refresh()
                        } else {
                            showToast(it.msg.noNull("删除失败"))
                        }
                    }

                    onComplete = {
                        dismissLoading()
                    }
                }

            }
        }
    }

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

    /**
     * 添加点击
     */
    fun onAddClick(view: View) {
        GjjTallyAddActivity.start(view.context)
    }

    /**
     * 货物发放点击
     */
    fun onGoodsSendClick(view: View) {
        pageModel.rv?.commonAdapter()?.items?.let {
            val checkedList = (it as List<GjjTallyBean>)
                .filter { b -> b.checked.get() }
                .toList()
            if (checkedList.isEmpty()) {
                showToast("请选择要发放的数据")
            } else if ((checkedList.filter { b -> b.fid == checkedList.first().fid }).size != checkedList.size) {
                showToast("请选择同一航班的数据")
            } else {

                showLoading()
                launchCollect({
                    NetApply.api.gjjTallyHandover(
                        mapOf(
                            "fid" to checkedList.first().fid,
                            "ids" to checkedList.map { b -> b.mfId },
                        ).toRequestBody()
                    )
                }) {
                    onSuccess = {
                        if (it.verifySuccess()) {
                            showToast(it.msg.noNull("发放成功"))
                            refresh()
                        } else {
                            showToast(it.msg.noNull("发放失败"))
                        }
                    }

                    onComplete = {
                        dismissLoading()
                    }
                }
            }
        }
    }

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

                else -> {}
            }
        }
    }

    /**
     * 删除条目
     */
    private fun onDeleteItem(bean: GjjTallyBean) {
        showLoading()
        launchCollect({
            NetApply.api.gjjTallyDelete(bean.mfId.noNull())
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("删除成功"))
                    refresh()
                } else {
                    showToast(it.msg.noNull("删除失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    private fun generateDesc(list: List<GjjTallyBean>?) {
        if (list.isNullOrEmpty()) {
            desc.value = "合计：0票，件数：0，重量：0KG"
            return
        }
        val total = list.size
        var totalJ = 0
        var totalW = 0.0

        list.forEach {
            totalJ += it.pc.noNull("0").toInt()
            totalW += it.weight?.toDouble() ?: 0.0
        }
        desc.value = "合计：${total}票，件数：${totalJ}，重量：${totalW.limit()}KG"
    }
}