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.holder.TallyAddListViewHolder
import com.lukouguoji.gjj.model.GjjTallyAddSelectDialogModel
import com.lukouguoji.gjj.model.TallyBatchDialogModel
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlatcarBean
import com.lukouguoji.module_base.bean.GjjHandoverRecordBean
import com.lukouguoji.module_base.bean.GjjTallyAddBean
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.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.finish
import com.lukouguoji.module_base.ktx.getActivity
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.toMap
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 dev.DevUtils
import dev.utils.common.NumberUtils

class GjjTallyAddViewModel : BasePageViewModel() {

    var tallyBean: GjjTallyBean? = null

    // 平板车或ULD
    val plateOrUld = MutableLiveData<String>()

    // 平板车信息
    val flatcarBean = MutableLiveData<FlatcarBean>()

    // 运单号或件号
    val waybillOrPiece = MutableLiveData<String>()

    val itemId = R.layout.item_tally_add

    val itemHolder = TallyAddListViewHolder::class.java

    private var isBatch = "1"

    override fun getData() {
        // 记录数据存在,则获取详情
        tallyBean?.let {
            showLoading()
            launchCollect({
                NetApply.api
                    .getGjjTallyDetail(it.mfId.noNull())
            }) {
                onSuccess = { result ->
                    if (result.verifySuccess() && !result.data.isNullOrEmpty()) {
                        val first = result.data!!.first()
                        val hashMapOf = hashMapOf<String, Any?>()
                        isBatch = first.isBatch.noNull("1")
                        first.initJianList()
                        hashMapOf.putAll(it.toMap())
                        hashMapOf.putAll(first.toMap())
                        val recordBean = NetApply.gson.fromJson(
                            hashMapOf.toJson(false),
                            GjjHandoverRecordBean::class.java
                        )
                        val addBean = GjjTallyAddBean(recordBean)
                        addBean.jianList.addAll(first.jianList)
                        pageModel.rv!!.commonAdapter()!!
                            .refresh(listOf(addBean))

                        plateOrUld.value = first.carID
                        flatcarBean.value = FlatcarBean().apply {
                            carId = first.carID.noNull()
                        }
                    } else {
                        showToast(result.msg.noNull("获取理货信息失败"))
                    }
                }
                onComplete = {
                    dismissLoading()
                }
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = adapter.items as List<GjjTallyAddBean>
        val bean = list[position]
        when (type) {
            R.id.iv_show -> {
                CheckUtil.handleSingleCheck(list, "show", position, true)
            }

            // 分批
            R.id.tv_batch -> {
                TallyBatchDialogModel(bean.handoverRecordBean) {
                    isBatch = "0"
                    adapter.notifyItemChanged(position)
                }.show()
            }

            // 删除
            R.id.tv_delete_order -> {
                Common.secondConfirmDialog(
                    DevUtils.getTopActivity(),
                    "是否确认删除该条信息?"
                ) { dialog ->
                    adapter.removeItem(position)
                    dialog.dismiss()
                }
            }

            // 删件
            R.id.tv_delete_matter -> {
                if (bean.jianList.none { it.checked.get() }) {
                    showToast("请先选择要删除的件号")
                    return
                }
                Common.secondConfirmDialog(
                    DevUtils.getTopActivity(),
                    "是否确认删除选中件号?"
                ) { dialog ->
                    bean.jianList.removeIf { it.checked.get() }
                    adapter.notifyItemChanged(position)
                    dialog.dismiss()
                }
            }

            else -> {}
        }
    }

    /**
     * 平板 扫描 点击
     */
    fun onPlateClick(view: View) {
        ScanModel.startScan(view.context.getActivity(), Constant.RequestCode.CAR)
    }

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

    /**
     * 确认点击
     */
    fun confirmClick(view: View) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val count = adapter.itemCount
        if (flatcarBean.value == null) {
            showToast("请先扫描平板车")
            return
        }
        if (count <= 0) {
            showToast("请先添加运单信息")
            return
        }

        val bean = adapter.items.first() as GjjTallyAddBean
        val jianListStr = bean.jianList.joinToString(",") { it.value }

        showLoading()
        launchCollect({
            val requestBody = mapOf(
                "carID" to flatcarBean.value!!.carId,
                "isBatch" to isBatch,
                "list" to jianListStr,
                "mfId" to bean.handoverRecordBean.mfId,
                "no" to bean.handoverRecordBean.no,
                "organizationcode" to bean.handoverRecordBean.organizationCode,
                "pc" to bean.handoverRecordBean.pc,
                "prefix" to bean.handoverRecordBean.prefix,
                "weight" to bean.handoverRecordBean.weight,
                "pcID" to bean.handoverRecordBean.pcID,
            ).toRequestBody()
            if (tallyBean == null) {
                NetApply.api.gjjTallyConfirm(requestBody)
            } else {
                NetApply.api.gjjTallyUpdate(requestBody)
            }
        }) {
            onSuccess = {
                dismissLoading()
                if (it.verifySuccess()) {
                    showToast("确认成功")
                    view.context.finish()
                } else {
                    showToast(it.msg.noNull("确认失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 取消点击
     */
    fun cancelClick(view: View) {
        view.context.finish()
    }

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

                Constant.RequestCode.WAYBILL -> {
                    val id = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                    waybillOrPiece.value = id
                    onWaybillOrPieceChange(false)
                }

                else -> {}
            }
        }
    }

    /**
     * 获取运单信息
     * @param waybillCode 运单号
     * @param jianCode 件号
     */
    private fun addWaybillInfo(waybillCode: String, jianCode: String = "") {
        val adapter = pageModel.rv!!.commonAdapter()!!
        if (adapter.itemCount > 0) {
            val bean = adapter.items.first() as GjjTallyAddBean
            if (bean.handoverRecordBean.getWaybillCode() == waybillCode) {
                bean.addJian(jianCode)
            } else {
                showToast("请先完成当前运单信息")
            }
            return
        }
        launchCollect({
            NetApply.api.getGjjTallyHandoverList(
                mapOf(
                    "prefix" to waybillCode.substring(0, 3),
                    "no" to waybillCode.substring(3),
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess() && !it.data.isNullOrEmpty()) {
                    if (it.data!!.size == 1) {
                        val bean = it.data!!.first()
                        val addBean = GjjTallyAddBean(bean)
                        if (jianCode.isNotEmpty()) {
                            addBean.addJian(jianCode)
                        }
                        adapter.addItem(addBean)
                    } else {
                        showSelectDialog(DevUtils.getTopActivity(), it.data!!, jianCode)
                    }
                } else {
                    showToast(it.msg.noNull("获取运单信息失败"))
                }
            }
        }
    }

    /**
     * 展示选择弹窗
     * 仅用于选择返回
     */
    private fun showSelectDialog(
        context: Context,
        list: List<GjjHandoverRecordBean>,
        jianCode: String = ""
    ) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        loge("展示选择弹窗 : ${list.size}")
        GjjTallyAddSelectDialogModel(list) { bean ->
            val addBean = GjjTallyAddBean(bean)
            if (jianCode.isNotEmpty()) {
                addBean.addJian(jianCode)
            }
            adapter.addItem(addBean)
        }.show(context)
    }

    /**
     * 获取平板车数据
     */
    private fun getFlatcarInfo(id: String) {
        if (id.isEmpty()) {
            return
        }
        launchCollect({
            NetApply.api
                .getFlatcarInfo(id)
        }) {
            onSuccess = {
                if (it.verifySuccess() && it.data != null) {
                    flatcarBean.value = it.data
                } else {
                    showToast(it.msg.noNull("获取平板车信息失败"))
                }
            }
        }
    }

    fun onPbcOrUldChange(focused: Boolean = false) {
        if (focused) {
            return
        }
        getFlatcarInfo(plateOrUld.value.noNull())
    }

    fun onWaybillOrPieceChange(focused: Boolean = false) {
        if (focused) {
            return
        }
        val code = waybillOrPiece.value.noNull()
        if (NumberUtils.isNumber(code)) {
            // 运单号
            if (code.length == 11) {
                addWaybillInfo(code)
            }
            // 运单号 + 件号
            else if (code.length == 16) {
                addWaybillInfo(code.substring(0, 11), code.substring(11))
            }
        }
    }

}