package cn.muchinfo.rma.view.base.home.commodity

import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.*
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.protobuf.protoclasses.ManageServiceMI2
import cn.muchinfo.rma.view.MyApplication
import cn.muchinfo.rma.view.autoWidget.toArrayList
import cn.muchinfo.rma.view.base.BaseViewModel
import cn.muchinfo.rma.view.base.home.commodity.viewholder.SpotInfoData
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mtp.polymer.com.autowidget.utils.TaskUiModel

class CommodityInformationViewModel : BaseViewModel() {

    /**
     * 加载状态控制
     */
    val loadingDialogStatus: MutableLiveData<TaskUiModel> = MutableLiveData()

    /**
     * 现货品种停用列表
     */
    val wrStandardDisableList: MutableLiveData<List<WrStandardData>> = MutableLiveData()

    /**
     * 现货品种正常列表
     */
    val wrStandardnormalList: MutableLiveData<List<WrStandardData>> = MutableLiveData()

    /**
     * 套保品种停用列表
     */
    val middleGoodsDisableList: MutableLiveData<List<MiddleGoodsData>> = MutableLiveData()

    /**
     * 套保品种正常列表
     */
    val middleGoodsNormalList: MutableLiveData<List<MiddleGoodsData>> = MutableLiveData()

    /**
     * 现货品种详情
     */
    val wrStandardDetails: MutableLiveData<WrStandardDetail> = MutableLiveData()

    /**
     * 套保品种详情
     */
    val middleGoodsDetails: MutableLiveData<MiddleGoodsDetails> = MutableLiveData()


    /**
     * 新增现货品种时的品牌列表数据
     */
    val brandModelList: MutableLiveData<List<SpotInfoData>> = MutableLiveData()

    /**
     * 新增现货品种时的型号列表数据
     */
    val spotModelList: MutableLiveData<List<SpotInfoData>> = MutableLiveData()

    /**
     * 新增现货品种时的套保品种信息
     */
    val middlegoodList: MutableLiveData<List<SpotInfoData>> = MutableLiveData()

    /**
     * 新增套保品种时的套保品种名称选择
     */
    val avalidGoodsList: MutableLiveData<List<AvaildGoodsGroupData>> = MutableLiveData()

    /**
     * 选择套保品种后的期货品种信息
     */
    val ggConvertConfigDataList: MutableLiveData<List<GGConvertConfigData>> = MutableLiveData()


    /**
     * 选择的套保品种
     */
    val avalidGoodsDetailsData: MutableLiveData<List<AvaildGoodsGroupData>> = MutableLiveData()

    /**
     * 变更记录列表
     */
    val changeLogDataList : MutableLiveData<List<ChangeLogData>> = MutableLiveData()


    /**
     * 新增套保品种时的套保品种名称选择
     */
    fun queryAvalidGoods() {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
        }
        MyApplication.getInstance()?.commodityManager?.queryAvalidGoods(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                avalidGoodsList.postValue(respData)
            }
        }
    }

    /**
     * 用于修改，恢复，停用套保品种的数据初始化，狗屎，，，，就不能外层列表带过来
     */
    fun queryMiddleGoodsDetail(
        middlegoodsid: String,
        select: (AvaildGoodsGroupData.() -> Unit)? = null
    ) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("middlegoodsid", middlegoodsid)
        }
        MyApplication.getInstance()?.commodityManager?.queryMiddleGoodsDetail(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                if (respData?.CvList?.size ?: 0 > 0) {
                    select?.invoke(respData?.CvList?.get(0) ?: AvaildGoodsGroupData())
                }
            }
        }

    }

    /**
     * 用于正常，停用套保品种详情的数据初始化
     */
    fun queryMiddleGoodsDetailList(
        middlegoodsid: String,
        select: (List<AvaildGoodsGroupData>.() -> Unit)? = null
    ) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("middlegoodsid", middlegoodsid)
        }
        MyApplication.getInstance()?.commodityManager?.queryMiddleGoodsDetail(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                select?.invoke(respData?.CvList ?: arrayListOf())
            }
        }

    }

    /**
     * 选择套保品种后的期货品种信息
     * @param goodsgroupid String
     */
    fun queryGGConvertConfig(goodsgroupid: String) {
        val params = mutableMapOf<String, String>().apply {
            put("goodsgroupid", goodsgroupid)
        }
        MyApplication.getInstance()?.commodityManager?.queryGGConvertConfig(params = params) { isSuccess, respData, _ ->
            if (isSuccess) {
                ggConvertConfigDataList.postValue(respData)
            }
        }
    }

    /**
     * 现货套保品种列表
     * type 1为添加，2为删除 ，3为更换资料
     */
    fun changeMiddleGoodsList(
        type: String,
        id: String,
        middlegoodsId: String = "",
        ano: String = "",
        enumdicname: String = "",
        middleGoodsName: String = ""
    ) {
        val oldDataList = middlegoodList.value?.toArrayList()
        val newDataList = arrayListOf<SpotInfoData>()
        if (type == "1") {
            oldDataList?.forEach {
                newDataList.add(it)
            }
            newDataList.add(SpotInfoData(id = id, value = ano, middleGoodsId = middlegoodsId))
        } else if (type == "2") {
            oldDataList?.forEach {
                if (id != it.id) {
                    newDataList.add(it.copy(id = oldDataList.indexOf(it).plus(1).toString()))
                }
            }
        } else if (type == "3") {
            oldDataList?.forEach {
                var newMiddlegoodsId = ""
                var newEnumdicname = ""
                var newMiddleGoodsName = ""
                var newData: SpotInfoData
                if (it.id == id) {
                    newMiddlegoodsId = if (middlegoodsId.isNullOrEmpty()) {
                        it.middleGoodsId
                    } else {
                        middlegoodsId
                    }
                    newMiddleGoodsName = if (middleGoodsName.isNullOrEmpty()) {
                        it.middleGoodsName
                    } else {
                        middleGoodsName
                    }
                    newEnumdicname = if (enumdicname.isNullOrEmpty()) {
                        it.enumdicname
                    } else {
                        enumdicname
                    }
                    newData = it.copy(
                        id = id,
                        value = ano,
                        middleGoodsId = newMiddlegoodsId,
                        enumdicname = newEnumdicname,
                        middleGoodsName = newMiddleGoodsName
                    )
                    newDataList.add(newData)
                } else {
                    newDataList.add(it)
                }
            }
        }
        middlegoodList.postValue(newDataList)
    }

    /**
     * 现货品种型号列表数据刷新
     * type 1为添加，2为删除 ，3为更换资料
     */
    fun changeSpotModelList(type: String, id: String, value: String) {
        val oldDataList = spotModelList.value?.toArrayList()
        val newDataList = arrayListOf<SpotInfoData>()
        if (type == "1") {
            oldDataList?.forEach {
                newDataList.add(it)
            }
            newDataList.add(SpotInfoData(id = id))
        } else if (type == "2") {
            oldDataList?.forEach {
                if (id != it.id) {
                    newDataList.add(it.copy(id = oldDataList.indexOf(it).plus(1).toString()))
                }
            }
        } else if (type == "3") {
            oldDataList?.forEach {
                if (it.id == id) {
                    newDataList.add(it.copy(value = value))
                } else {
                    newDataList.add(it)
                }

            }
        }
        spotModelList.postValue(newDataList)
    }

    /**
     * 现货品种品牌列表数据刷新
     * type 1为添加，2为删除 ，3为更换资料
     */
    fun changeBrandModelList(type: String, id: String, value: String) {
        val oldDataList = brandModelList.value?.toArrayList()
        val newDataList = arrayListOf<SpotInfoData>()
        if (type == "1") {
            oldDataList?.forEach {
                newDataList.add(it)
            }
            newDataList.add(SpotInfoData(id = id))
        } else if (type == "2") {
            oldDataList?.forEach {
                if (id != it.id) {
                    newDataList.add(it.copy(id = oldDataList.indexOf(it).plus(1).toString()))
                }
            }
        } else if (type == "3") {
            oldDataList?.forEach {
                if (it.id == id) {
                    newDataList.add(it.copy(value = value))
                } else {
                    newDataList.add(it)
                }

            }
        }
        brandModelList.postValue(newDataList)
    }

    /**
     * 对于现货列表点击展开后的数据处理
     * @param index Int 点击的item数据在列表的index
     * @param status String 0-停用 1-正常
     */
    fun resetwrStandardDataList(index: Int, status: String) {
        val datanewlist = arrayListOf<WrStandardData>()
        when (status) {
            "0" -> {
                wrStandardDisableList.value?.forEach {
                    if (index == wrStandardDisableList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                wrStandardDisableList.postValue(datanewlist)
            }
            "1" -> {
                wrStandardnormalList.value?.forEach {
                    if (index == wrStandardnormalList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                wrStandardnormalList.postValue(datanewlist)
            }
        }
    }

    /**
     * 对于套保列表点击展开后的数据处理
     * @param index Int 点击的item数据在列表的index
     * @param status String 0-停用 1-正常
     */
    fun resetMiddleGoodsDataList(index: Int, status: String) {
        val datanewlist = arrayListOf<MiddleGoodsData>()
        when (status) {
            "0" -> {
                middleGoodsDisableList.value?.forEach {
                    if (index == middleGoodsDisableList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                middleGoodsDisableList.postValue(datanewlist)
            }
            "1" -> {
                middleGoodsNormalList.value?.forEach {
                    if (index == middleGoodsNormalList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                middleGoodsNormalList.postValue(datanewlist)
            }
        }
    }

    /**
     * 查询现货品种
     * @param status String  0-停用 1-正常
     */
    fun queryWrStandard(
        status: String
    ) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("status", status)
        }
        MyApplication.getInstance()?.commodityManager?.queryWrStandard(params = params) { isSuccess, respData, _ ->
            if (isSuccess) {
                if (status == "0") {
                    wrStandardDisableList.postValue(respData)
                } else if (status == "1") {
                    wrStandardnormalList.postValue(respData)
                }
            }
        }
    }

    /**
     * 查询现货品种详情
     * @param wrstandardid String
     */
    fun queryWrStandardDetails(wrstandardid: String) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("wrstandardid", wrstandardid)
        }
        MyApplication.getInstance()?.commodityManager?.queryWrStandardDetail(params = params) { isSuccess, respData, _ ->
            if (isSuccess) {
                wrStandardDetails.postValue(respData)
                initSpotGoodsActivity(respData ?: WrStandardDetail())
            }
        }
    }

    /**
     * 用来在现货品种信息的修改，恢复，停用，详情时的页面数据回填
     */
    fun initSpotGoodsActivity(respData: WrStandardDetail) {
        val newbrandModelList = arrayListOf<SpotInfoData>()
        val newspotModelList = arrayListOf<SpotInfoData>()
        val newmiddlegoodList = arrayListOf<SpotInfoData>()
        respData.gbList.forEach {
            newbrandModelList.add(
                SpotInfoData(
                    id = respData.gbList.indexOf(it).plus(1).toString(),
                    value = it.brandname
                )
            )
        }
        respData.gtList.forEach {
            newspotModelList.add(
                SpotInfoData(
                    id = respData.gtList.indexOf(it).plus(1).toString(),
                    value = it.modelname
                )
            )
        }
        respData.wrsList.forEach {
            newmiddlegoodList.add(
                SpotInfoData(
                    id = respData.wrsList.indexOf(it).plus(1).toString(),
                    value = it.convertratio,
                    middleGoodsId = it.middlegoodsid,
                    middleGoodsName = it.middlegoodsname,
                    enumdicname = ""
                )
            )
        }
        brandModelList.postValue(newbrandModelList)
        spotModelList.postValue(newspotModelList)
        middlegoodList.postValue(newmiddlegoodList)
    }

    /**
     * 查询套保品种列表
     * @param status String 0-停用 1-正常
     */
    fun queryMiddleGoodsList(status: String) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("status", status)
        }
        MyApplication.getInstance()?.commodityManager?.queryMiddleGoods(params = params) { isSuccess, respData, _ ->
            if (isSuccess) {
                if (status == "0") {
                    middleGoodsDisableList.postValue(respData)
                } else if (status == "1") {
                    middleGoodsNormalList.postValue(respData)
                }
            }
        }
    }


    /**
     * 查询套保品种详情
     * @param middlegoodsid String
     */
    fun queryMiddleGoodsDetails(middlegoodsid: String) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("middlegoodsid", middlegoodsid)
        }
        MyApplication.getInstance()?.commodityManager?.queryMiddleGoodsDetails(params = params) { isSuccess, respData, _ ->
            if (isSuccess) {
                middleGoodsDetails.postValue(respData)
            }
        }
    }

    /**
     * 套保品种新增请求
     * @param middlegoodsname String 套保品种名称
     * @param middlegoodscode String 套保品种代码
     * @param goodsunitid Int 单位ID
     * @param relatedgoodsid Long 关联交易商品ID
     * @param evaluateratio Double 估价系数
     * @param qtydecimalplace Int 数量小数位
     * @param creatorid Long 创建人
     * @param modifierid Long 修改人
     * @param relatedgoodstype Int 关联商品类型 - 1:期货合约 2:现货品种
     * @param needhedgeratio Double 套保比率
     * @param areauserid Long 机构用户ID
     * @param goodsgroupid Long 关联期货品种ID
     * @param remark String 备注
     */
    fun requestErmsMiddelGoodsReq(
        middlegoodsname: String = "",
        middlegoodscode: String = "",
        goodsunitid: Int = 0,
        relatedgoodsid: Long = 0,
        evaluateratio: Double = 0.0,
        qtydecimalplace: Int = 0,
        creatorid: Long = 0,
        modifierid: Long = 0,
        relatedgoodstype: Int = 0,
        needhedgeratio: Double = 0.0,
        areauserid: Long = 0,
        goodsgroupid: Long = 0,
        remark: String = "",
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.commodityManager?.requestErmsMiddelGoodsReq(
                middlegoodsname,
                middlegoodscode,
                goodsunitid,
                relatedgoodsid,
                evaluateratio,
                qtydecimalplace,
                creatorid,
                modifierid,
                relatedgoodstype,
                needhedgeratio,
                areauserid,
                goodsgroupid,
                remark
            ) { isCompleted, err ->
                if (isCompleted) {
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                } else {
                    loadingDialogStatus.postValue(
                        TaskUiModel.failed(
                            InteractiveException(
                                errorMessage = err?.message!!
                            )
                        )
                    )
                }
            }
        }
    }

    /**
     * 套保品种停用请求
     * @param middlegoodsid Long 套保品种ID
     * @param isvalid Int  0:无效 1:有效
     * @param modifierid Long 修改人
     */
    fun requestErmsMiddelGoodsStopReq(
        middlegoodsid: Long = 0,
        isvalid: Int = 0,
        modifierid: Long = 0,
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.commodityManager?.requestErmsMiddelGoodsStopReq(
                middlegoodsid = middlegoodsid,
                isvalid = isvalid,
                modifierid = modifierid
            ) { isCompleted, err ->
                if (isCompleted) {
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                } else {
                    loadingDialogStatus.postValue(
                        TaskUiModel.failed(
                            InteractiveException(
                                errorMessage = err?.message!!
                            )
                        )
                    )
                }
            }
        }
    }

    /**
     * 套保品种修改请求
     * @param middlegoodsid Long 套保品种ID
     * @param goodsunitid Int 单位ID
     * @param relatedgoodsid Long 关联交易商品ID
     * @param evaluateratio Double 估价系数
     * @param qtydecimalplace Int 数量小数位
     * @param modifierid Long 修改人
     * @param relatedgoodstype Int 关联商品类型 - 1:期货合约 2:现货品种
     * @param needhedgeratio Double 套保比率
     * @param areauserid Long 机构用户ID
     * @param goodsgroupid Long 关联期货品种ID
     * @param remark String 备注
     * @return Packet50
     */
    fun requestErmsMiddelGoodsEditReq(
        middlegoodsid: Long = 0,
        goodsunitid: Int = 0,
        relatedgoodsid: Long = 0,
        evaluateratio: Double = 0.0,
        qtydecimalplace: Int = 0,
        modifierid: Long = 0,
        relatedgoodstype: Int = 0,
        needhedgeratio: Double = 0.0,
        areauserid: Long = 0,
        goodsgroupid: Long = 0,
        remark: String = "",
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.commodityManager?.requestErmsMiddelGoodsEditReq(
                middlegoodsid,
                goodsunitid,
                relatedgoodsid,
                evaluateratio,
                qtydecimalplace,
                modifierid,
                relatedgoodstype,
                needhedgeratio,
                areauserid,
                goodsgroupid,
                remark
            ) { isCompleted, err ->
                if (isCompleted) {
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                } else {
                    loadingDialogStatus.postValue(
                        TaskUiModel.failed(
                            InteractiveException(
                                errorMessage = err?.message!!
                            )
                        )
                    )
                }
            }
        }
    }

    /**
     * 现货品种申请请求
     * @param deliverygoodscode String 交割商品代码(新增时有值)
     * @param deliverygoodsname String 交割商品名称(新增时有值)
     * @param wrstandardid Long 现货商品ID(修改时有值)
     * @param unitid Long 单位ID(修改时有值)
     * @param type Int 类型 1 新增 2 修改
     * @param remark String 备注
     * @param spotgoodsmodels List<SpotGoodsModelEx> SpotGoodsModelEx 现货商品型号数据
     * @param spotgoodsbrands List<SpotGoodsBrandEx> SpotGoodsBrandEx 现货商品品牌数据
     * @param wrsconvertdetails List<WRSConvertDetailEx> WRSConvertDetailEx 现货商品折算配置明细数据
     */
    fun requestGoodsApply(
        deliverygoodscode: String = "",
        deliverygoodsname: String = "",
        wrstandardid: Long = 0,
        unitid: Long = 0,
        type: Int = 0,
        remark: String = "",
        spotgoodsmodels: List<ManageServiceMI2.SpotGoodsModelEx> = arrayListOf(),
        spotgoodsbrands: List<ManageServiceMI2.SpotGoodsBrandEx> = arrayListOf(),
        wrsconvertdetails: List<ManageServiceMI2.WRSConvertDetailEx> = arrayListOf(),
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.commodityManager?.requestGoodsApply(
                deliverygoodscode,
                deliverygoodsname,
                wrstandardid,
                unitid,
                type,
                remark,
                spotgoodsmodels,
                spotgoodsbrands,
                wrsconvertdetails
            ) { isCompleted, err ->
                if (isCompleted) {
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                } else {
                    loadingDialogStatus.postValue(
                        TaskUiModel.failed(
                            InteractiveException(
                                errorMessage = err?.message!!
                            )
                        )
                    )
                }
            }
        }
    }

    /**
     * 现货商品停用，复用请求
     * @param wrstandardid Long
     * @param isvalid Int
     * @param isSuccess Function1<[@kotlin.ParameterName] Boolean, Unit>
     */
    fun requestGoodsCancelReq(
        wrstandardid: Long = 0,
        isvalid: Int = 0,
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.commodityManager?.requestGoodsCancelReq(
                wrstandardid = wrstandardid,
                isvalid = isvalid
            ){ isCompleted, err ->
                if (isCompleted) {
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                } else {
                    loadingDialogStatus.postValue(
                        TaskUiModel.failed(
                            InteractiveException(
                                errorMessage = err?.message!!
                            )
                        )
                    )
                }
            }
        }
    }

    /**
     * 查询变更记录
     * @param RelatedId String
     */
    fun queryChangeLog(RelatedId : String){
        val params = mutableMapOf<String, String>().apply {
            put("RelatedId", RelatedId)
        }

        MyApplication.getInstance()?.commonManager?.queryChangeLog(params = params){isSuccess, respData, error ->
            if (isSuccess){
                changeLogDataList.postValue(respData)
            }
        }
    }

}