package com.lukouguoji.gjj.viewModel

import android.content.Context
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.activity.GjjManifestListActivity
import com.lukouguoji.gjj.holder.GjjPacketParseViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlightBean
import com.lukouguoji.module_base.bean.PacketParseBean
import com.lukouguoji.module_base.http.net.NetApply
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.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.Calendar
import java.util.Date

class GjjPacketParseViewModel : BasePageViewModel() {

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

    // 航班号
    var flightNo = MutableLiveData("")

    // 报文类型
    var packetType = MutableLiveData("")

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

    // 报文内容
    var packetContent = MutableLiveData<String>()

    // 是否可修改
    var modifyAble = MutableLiveData(false)

    // 修改对应的position
    var position = -1

    val itemId = R.layout.item_packet_parse
    val itemHolder = GjjPacketParseViewHolder::class.java

    // 报文类型
    val packetTypeList = MutableLiveData<List<KeyValue>>(emptyList())

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

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

    // 数量
    val count = MutableLiveData(0)

    /**
     * 初始化
     */
    fun init(context: Context) {
        DictUtils.getPacketTypeList {
            packetTypeList.value = it
        }

        // 监听修改的内容,并设置到对应的数据中
        packetContent.observe(context.getLifecycleOwner()) {
            if (!modifyAble.value!!) {
                return@observe
            }
            val adapter = pageModel.rv?.commonAdapter()
            if ((adapter?.items?.size ?: 0) <= position) {
                return@observe
            }
            val item = adapter?.getItem(position)
            if (position >= 0 && item != null) {
                (item as PacketParseBean).text = it
            }
        }
    }

    /**
     * 获取航班信息
     */
    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
                } else {
                    flightBean.value = FlightBean()
                    departureList.value = emptyList()
                    showToast(it.msg.noNull("获取航班信息失败"))
                }
            }

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

    override fun getData() {
        if (!verifyHaveFlight()) {
            showToast("请输入航班号")
            pageModel.finishLoading()
            return
        }
        launchCollect({
            NetApply.api
                .getGjcPacketParseList(
                    mapOf(
                        "fdate" to flightDate.value,
                        "fno" to flightNo.value,
                        "msgType" to packetType.value.noNull("ALL"),
                    ).toRequestBody()
                )
        }) {
            onSuccess = {
                pageModel.handleDataList(it.data)
                count.value = it.data?.size ?: 0
                resetContent()
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as PacketParseBean
        when (type) {
            R.id.ll -> {
                this.position = position
                packetContent.postValue(bean.text.noNull())
                modifyAble.postValue(false)
            }

            R.id.iv_icon -> {
                bean.checked.set(!bean.checked.get())
            }

            else -> {}
        }
    }

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

    /**
     * 报文类型点击
     */
    fun onPacketTypeSelected(position: Int) {
        packetType.value = packetTypeList.value?.get(position)?.value
    }

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

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

    /**
     * 列表点击
     */
    fun onListClick(view: View) {
        GjjManifestListActivity.start(view.context)
    }

    /**
     * 修改点击
     */
    fun onModifyClick(view: View) {
        modifyAble.value = !modifyAble.value!!
    }

    /**
     * 确认点击
     */
    fun onConfirmClick(view: View) {
        if (!verifyHaveFlight()) {
            showToast("请输入正确航班信息")
            return
        }
        val filter =
            pageModel.rv!!.commonAdapter()!!.items.filter { (it as PacketParseBean).checked.get() } as List<PacketParseBean>
        if (filter.isEmpty()) {
            showToast("请选择需要生成的报文")
            return
        }
        val ffmList = filter.filter { it.msgType == "FFM" }
        if (ffmList.isNotEmpty()) {
            submitFFM(ffmList)
        }
        val fwbList = filter.filter { it.msgType == "FWB" || it.msgType == "FHL" }
        if (fwbList.isNotEmpty()) {
            submitFWB(fwbList)
        }
    }

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

    /**
     * 提交FWB报文
     */
    private fun submitFWB(fwbList: List<PacketParseBean>) {
        val body = fwbList.toJson(false)
            .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        launchCollect({
            NetApply.api
                .gjjPacketParseFWBSubmit(body)
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("提交成功"))
                    refresh()
                } else {
                    showToast(it.msg.noNull("提交失败"))
                }
            }
        }
    }

    /**
     * 提交FFM报文
     */
    private fun submitFFM(ffmList: List<PacketParseBean>) {
        val body = mapOf(
            "ffmstrL" to ffmList.map { it.text }.toList(),
            "poolIdList" to ffmList.map { it.id }.toList(),
            "fid" to flightBean.value?.fid
        ).toRequestBody()
        launchCollect({
            NetApply.api
                .gjjPacketParseFFMSubmit(body)
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast(it.msg.noNull("提交成功"))
                    refresh()
                } else {
                    showToast(it.msg.noNull("提交失败"))
                }
            }
        }
    }

    private fun resetContent() {
        modifyAble.postValue(false)
        packetContent.postValue("")
        position = -1
    }
}