package com.sixin.module_p.ui.gnj.xieji.add

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.FlatcarBean
import com.lukouguoji.module_base.bean.FlightBean
import com.lukouguoji.module_base.bean.GnjUnloadListBean
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.formatDate
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showConfirmDialog
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.Common
import com.lukouguoji.module_base.util.DictUtils
import com.sixin.module_p.R
import dev.DevUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.util.Calendar
import kotlin.properties.Delegates

class PdaGnjXieJiAddViewModel : BaseViewModel(), IOnItemClickListener {

    val date = MutableLiveData(DateUtils.getCurrentTime().formatDate())
    val fno = MutableLiveData("")
    val car = MutableLiveData("")

    val count = MutableLiveData(0)

    val itemViewHolder = PdaGnjXieJiAddViewHolder::class.java
    val itemLayoutId = R.layout.item_pda_gnj_xieji_add

    //货物类型：0“国际货”，1“活体鲜活”，2“贵重物品”，3“其他特货”
    var cargoType = MutableLiveData("")

    var cargoTypeString = MutableLiveData("")

    private lateinit var checkedItems : BooleanArray

    var clearable = MutableLiveData(false)

    private val cargoTypeList = MutableLiveData<List<KeyValue>>()

    var rv: RecyclerView by Delegates.notNull()
    val flight = MutableLiveData(FlightBean())

//    业务袋
    val check = MutableLiveData(false)

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

    fun onInit(intent: Intent) {
        FlowBus.with<String>(ConstantEvent.SCAN_CODE_RESULT)
            .onEach {
                car.value = it
                onCarInputFinished()
            }
            .launchIn(viewModelScope)

        DictUtils.getDicCargoTypeList {
            cargoTypeList.value = it
            checkedItems = BooleanArray(it.size)
            val dataBeanString = intent.getStringExtra(Constant.Key.DATA) ?: ""
            val unloadList = NetApply.gson.fromJson(dataBeanString, GnjUnloadListBean::class.java)
            if (unloadList.fid !== "") {
                date.value = unloadList.fdate
                fno.value = unloadList.fno
                queryFlight()
            }
        }

    }

    /**
     * 板车号输入完成
     * 焦点失去
     */
    fun onCarInputFinished() {
        if (car.value.isNullOrEmpty()) {
            return
        }
        if (rv.commonAdapter()?.items?.find { (it as FlatcarBean).carId == car.value } != null) {
            showToast("该平板车已添加")
            return
        }
        launchLoadingCollect({
            NetApply.api.getFlatcarInfo(car.value.noNull())
        }) {
            onSuccess = {
                rv.commonAdapter()?.addItem(it.data)
                count.value = count.value?.plus(1)
            }
            onComplete = {
                car.value = ""
            }
        }
    }

    /**
     * 查询航班信息
     */
    fun queryFlight() {
        if (date.value.isNullOrEmpty() || fno.value.isNullOrEmpty()) {
            return
        }
        launchLoadingCollect({
            NetApply.api.getGnFlightBean(
                mapOf(
                    "fdate" to date.value,
                    "fno" to fno.value,
                    "fdest" to "HFE"
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    val data = it.data!!
                    if (data.countryType == "0" && data.fdest == "HFE") {
                        flight.value = it.data

                        //查询对应航班的卸机信息
                        launchLoadingCollect({
                            NetApply.api.getGnjUnloadCarList(
                                mapOf(
                                    "fdate" to date.value,
                                    "fno" to fno.value,
                                ).toRequestBody()
                            )
                        }) {
                            onSuccess = {
//                    获取单证交接--根据上面查出来的航班fid
                                launchCollect({NetApply.api.getHandover(flight.value!!.fid)}){
                                    onSuccess = { iit ->
                                        check.value = iit.data != null
                                    }
                                }
//                                println(it.list)
//                                根据航班查询卸机后根据第一条的货物类型来塞值
                                val first = it.list?.firstOrNull()
                                if (first != null) {
                                    cargoType.value = first.cargoType
                                    cargoTypeString.value = first.cargoTypeName
                                    checkedItems = cargoTypeList.value?.size?.let {
                                        BooleanArray(it) { index ->
                                            first.cargoType.contains(cargoTypeList.value!![index].value)
                                        }
                                    }!!
                                    if (first.cargoType !== "") {
                                        clearable.value = true
                                    }
                                    if (first.cargoTypeName === "") {
                                        cargoTypeString.value = cargoTypeList.value?.filter { item -> first.cargoType.contains(item.value) }
                                            ?.joinToString(",") { it1 -> it1.key }
                                    }
                                }
                                for (item in it.list!!){
                                    launchLoadingCollect({
                                        NetApply.api.getFlatcarInfo(item.carId)
                                    }) {
                                        onSuccess = {
                                            var flatcarBean = it.data as FlatcarBean
                                            flatcarBean.addFalg = false
                                            flatcarBean.xieJiId = item.id
                                            rv.commonAdapter()?.addItem(flatcarBean)
                                            count.value = count.value?.plus(1)
                                        }
                                    }
                                }
                            }
                        }

                    } else {
                        showToast("该航班不是国内进港航班")
                    }
                } else {
                    showToast(it.msg.noNull("获取数据失败"))
                }
            }
        }
    }

    fun onDateClick() {
        Common.onYearMonthDay(DevUtils.getTopActivity(), date.value) { year, month, day ->
            val calendar = Calendar.getInstance()
            calendar.set(year, month - 1, day)
            date.value = calendar.time.formatDate()
            queryFlight()
        }
    }

    fun onCargoTypeClick() {
        showAlertDialog()
    }

    private fun showAlertDialog() {
        val items = cargoTypeList.value
        val displayValues = items?.map { it.key }?.toTypedArray()
        val nowCheckedItems = checkedItems.clone()
        AlertDialog.Builder(getTopActivity())
            .setTitle("请选择")
            .setMultiChoiceItems(displayValues, nowCheckedItems) { _, which, isChecked ->
                // 当选项被点击时更新选中状态
                nowCheckedItems[which] = isChecked
            }
            .setPositiveButton("确定") { dialog, _ ->
                checkedItems = nowCheckedItems
                // 遍历选中的项目
                val selectedItems = items?.filterIndexed { index, _ -> checkedItems[index] } ?.joinToString(separator = ",") { it.value }
                val selectedItemsString = items?.filterIndexed { index, _ -> checkedItems[index] } ?.joinToString(separator = ",") { it.key }
                // 显示选择结果
                if (selectedItems != null) {
                    if (selectedItems.isNotEmpty()) {
                        cargoType.value = selectedItems
                        cargoTypeString.value = selectedItemsString
                        clearable.value = true
                    }
                }
                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .create()
            .show()
    }

    fun clearChecked() {
        checkedItems = cargoTypeList.value?.size?.let { BooleanArray(it) }!!
        cargoTypeString.value = ""
        cargoType.value = ""
        clearable.value = false
    }

    private fun verifyHandover () {
        //        业务袋（单证交接）--勾选上则新增，不够选择删除
        if (check.value == true) {
            launchCollect({
                NetApply.api.anyPost(
                    "flt/insertHandover",
                    mapOf(
                        "fileType" to "1",
                        "fid" to flight.value!!.fid,
                        "ieFlag" to "I"
                    ).toRequestBody()
                )
            }) {
                onSuccess = {}
                onFailed = { _: Int, _: String -> }
            }
        } else {
            launchCollect({
                NetApply.api.anyPostForId( "/flt/deleteHandoverByFid", flight.value!!.fid)
            }) {
                onSuccess = {}
                onFailed = { _: Int, _: String -> }
            }
        }
    }

    fun onConfirmClick() {
        if (flight.value!!.fid.verifyNullOrEmpty("请录入航班信息")) {
            return
        }
        if (rv.commonAdapter()?.items?.isNullOrEmpty() == true) {
            showToast("请添加平板车数据")
            return
        }
//        业务袋（单证交接）
        verifyHandover()
        // addFalg为true的才新增
        var filteredList = ArrayList<FlatcarBean>()
        var airCraftIdList = ArrayList<Long>()
        for (item in rv.commonAdapter()?.items!!){
            item as FlatcarBean
            println("进港卸机id："+item.xieJiId)
            if (item.addFalg) {
                filteredList.add(item)
            }else{
                airCraftIdList.add(item.xieJiId.toLong())
            }
        }

        //对货物类型判空，走修改接口
        if(! cargoType.value.isNullOrEmpty() ){
            launchLoadingCollect({
                NetApply.api.anyPost(
                    "unloadingAirCraft/update", mapOf(
                        "cargoType" to cargoType.value,
                        "airCraftIdList" to airCraftIdList,
                    ).toRequestBody(true)
                )
            }) {
                onSuccess = {
                    println("修改货物类型成功！")
                }
            }
        }

        if (filteredList.size == 0){
            DevUtils.getTopActivity().finish()
//            showToast("请添加平板车数据")
            return
        }

        launchLoadingCollect({
            NetApply.api.anyPost(
                "unloadingAirCraft/completed", mapOf(
                    "fdate" to flight.value!!.fdate,
                    "fid" to flight.value!!.fid,
                    "fno" to flight.value!!.fno,
                    "cargoType" to cargoType.value,
                    "flatcarList" to filteredList,
                ).toRequestBody(true)
            )
        }) {
            onSuccess = {
                showToast(it.msg.noNull("确认装板成功"))
                DevUtils.getTopActivity().finish()
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val adapter = rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as FlatcarBean
        when (type) {
            R.id.tv_delete -> {
                getTopActivity().showConfirmDialog(
                    "是否删除该条记录？"
                ) {


                    if (bean.xieJiId.isNotBlank()){
                        launchLoadingCollect({
                            NetApply.api.anyGetForId(
                                "unloadingAirCraft/deleteById", bean.xieJiId
                            )
                        }) {
                            onSuccess = {
                                showToast(it.msg.noNull("删除成功"))
                                rv.commonAdapter()?.removeItem(position)
                                count.value = count.value?.minus(1)
                            }
                        }
                    }
                }
            }

            else -> {}
        }
    }

    fun scanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.CAR)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        loge(
            "扫码返回信息 : $resultCode ; ${data != null} ; ${
                data?.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
            }"
        )
        if (data == null || resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            Constant.RequestCode.CAR -> {
                car.value = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                onCarInputFinished()
            }

            else -> {}
        }
    }
}