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

import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.business.hedge.HedgePlanInfo
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.HedgePlanData
import cn.muchinfo.rma.global.data.WrStandardData
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.view.MyApplication
import cn.muchinfo.rma.view.base.BaseViewModel
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mtp.polymer.com.autowidget.dialog.SelectData
import mtp.polymer.com.autowidget.utils.TaskUiModel

class HedgePlanViewModel : BaseViewModel() {

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

    /**
     * 客户合同列表未提交数据
     */
    val unSubmitList: MutableLiveData<List<HedgePlanData>> = MutableLiveData()

    /**
     * 客户合同列表待审核数据
     */
    val toAuditList: MutableLiveData<List<HedgePlanData>> = MutableLiveData()

    /**
     * 客户合同列表履约中数据
     */
    val executionList: MutableLiveData<List<HedgePlanData>> = MutableLiveData()

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


    /**
     * 对于列表点击展开后的数据处理
     * @param index Int 点击的item数据在列表的index
     * @param type String 点击的列表类型
     *
     */

    fun resetDataList(index: Int, type: String) {
        val datanewlist = arrayListOf<HedgePlanData>()
        when (type) {
            "0" -> {
                unSubmitList.value?.forEach {
                    if (index == unSubmitList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                unSubmitList.postValue(datanewlist)
            }
            "1" -> {
                toAuditList.value?.forEach {
                    if (index == toAuditList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                toAuditList.postValue(datanewlist)
            }
            "2" -> {
                executionList.value?.forEach {
                    if (index == executionList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                executionList.postValue(datanewlist)
            }
        }

    }

    /**
     * 0:未提交 1:待审核 2:执行中
     * @param type String
     */
    fun queryHedegList(type: String) {
        val params = mutableMapOf<String, String>().apply {
            put("userId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            if (type == "0"){
                put("HedgePlanStatus", "0,6")
            } else if (type == "1"){
                put("HedgePlanStatus", "1,4")
            }else{
                put("HedgePlanStatus", type)
            }

        }
        MyApplication.getInstance()?.hedgeManager?.queryHedgeList(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                when (type) {
                    "0" -> {
                        unSubmitList.postValue(respData)
                    }
                    "1" -> {
                        toAuditList.postValue(respData)
                    }
                    "2" -> {
                        executionList.postValue(respData)
                    }
                }
            }
        }
    }


    /**
     * 查询现货品种列表
     */
    fun queryWrStandardList() {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("status", "1")
        }
        MyApplication.getInstance()?.commodityManager?.queryWrStandard(params) { isSuccess, respData, error ->
            if (isSuccess) {
                wrStandardDataList.postValue(respData)
            }
        }
    }

    /**
     * 根据选择控件进行数据重新组装（现货品种列表）
     * @param dataList List<UserInfoData>
     * @return ArrayList<SelectData>
     */
    fun selectSpotVarietiesList(dataList: List<WrStandardData>): ArrayList<SelectData> {
        val newSpotVarietiesList = arrayListOf<SelectData>()
        dataList.forEach {
            newSpotVarietiesList.add(
                SelectData(
                    id = it.wrstandardid ?: "",
                    value = it.wrstandardname ?: "",
                    deliverygoodsid = it.deliverygoodsid ?: "",
                    areauserid = it.areauserid ?: "",
                    enumdicname = it.enumdicname ?: ""
                )
            )
        }
        return newSpotVarietiesList
    }


    /**
     *
     * @param hedgePlanData HedgePlanInfo 套保计划信息资料
     * @param hedgePlanID Long 套保计划id
     * @param operateType Int 操作类型-1:保存草稿2:提交申请3:审核通过4:审核拒绝5:撤回
     * @param remark String 备注
     * @param isSuccess [@kotlin.ExtensionFunctionType] Function1<Boolean, Unit>?
     */
    fun orderHedge(
        hedgePlanData: HedgePlanInfo = HedgePlanInfo(),
        hedgePlanID: Long = 0,
        operateType: Int = 0,
        remark: String = "",
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.hedgeManager?.orderHedge(hedgePlanData = hedgePlanData,hedgePlanID = hedgePlanID,operateType = operateType,remark = remark){isCompleted, err ->
                if (isCompleted){
                    ToastUtils.showLong("请求成功")
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                }else{
                    loadingDialogStatus.postValue(TaskUiModel.failed(InteractiveException(errorMessage = err?.message!!)))
                }
            }
        }
    }


}