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

import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.business.contract.SpotContractInfo
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.ContractData
import cn.muchinfo.rma.global.data.UserInfoData
import cn.muchinfo.rma.global.data.WrStandardData
import cn.muchinfo.rma.global.data.WrStandardDetail
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.view.MyApplication
import cn.muchinfo.rma.view.base.BaseViewModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mtp.polymer.com.autowidget.dialog.SelectData
import mtp.polymer.com.autowidget.utils.TaskUiModel

class ContractViewModel : BaseViewModel() {

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

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

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

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

    /**
     * 客户合同列表已完成数据
     */
    val finishList: MutableLiveData<List<ContractData>> = MutableLiveData()

    /**
     * 选择的定价类型
     */
    val pricingType: MutableLiveData<SelectData> = MutableLiveData()

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

    /**
     * 查询客户资料列表(正常的列表
     */
    val normalUserInfoList: MutableLiveData<List<UserInfoData>> = MutableLiveData()

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

    /**
     * 对于列表点击展开后的数据处理
     * @param index Int 点击的item数据在列表的index
     * @param type String 点击的列表类型
     */
    fun resetDataList(index: Int, type: String) {
        val datanewlist = arrayListOf<ContractData>()
        when (type) {
            "1" -> {
                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)
            }
            "2" -> {
                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)
            }
            "3" -> {
                performanceList.value?.forEach {
                    if (index == performanceList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                performanceList.postValue(datanewlist)
            }
            "4" -> {
                finishList.value?.forEach {
                    if (index == finishList.value?.indexOf(it)) {
                        if (it.indexSelect == 0) {
                            datanewlist.add(it.copy(indexSelect = 1))
                        } else {
                            datanewlist.add(it.copy(indexSelect = 0))
                        }
                    } else {
                        datanewlist.add(it)
                    }
                }
                finishList.postValue(datanewlist)
            }
        }

    }


    /**
     * 现货合同查询
     * @param QueryType String 查询类型 1-未提交 2-待审核 3-履约中 4-已完成
     */
    fun queryContract(QueryType: String) {

        val params = mutableMapOf<String, String>().apply {
            put("userId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("QueryType", QueryType)
        }

        MyApplication.getInstance()?.contractManager?.queryContract(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                when (QueryType) {
                    "1" -> {
                        unSubmitList.postValue(respData)
                    }
                    "2" -> {
                        toAuditList.postValue(respData)
                    }
                    "3" -> {
                        performanceList.postValue(respData)
                    }
                    "4" -> {
                        finishList.postValue(respData)
                    }
                }
            } else {
                loadingDialogStatus.value =
                    TaskUiModel.failed(InteractiveException(errorMessage = error?.message ?: ""))
            }
        }
    }


    /**
     * 查询客户资料列表(正常的列表)用来页面选择客户
     */
    fun queryUserInfo() {
        val params = mutableMapOf<String, String>().apply {
            put("MemberUserID", GlobalDataCollection.instance?.loginRsp?.memberUserID.toString())
            put("queryType", "3")
        }

        MyApplication.getInstance()?.customerManage?.queryUserInfo(params) { isSuccess, respData, error ->
            if (isSuccess) {
                normalUserInfoList.postValue(respData)
            }
        }
    }

    /**
     * 根据选择控件进行数据重新组装（客户）
     * @param dataList List<UserInfoData>
     * @return ArrayList<SelectData>
     */
    fun setSelectCustomerList(dataList: List<UserInfoData>): ArrayList<SelectData> {
        val newCustomerList = arrayListOf<SelectData>()
        dataList.forEach {
            newCustomerList.add(SelectData(id = it.userid.toString() ?: "", value = it.customername ?: ""))
        }
        return newCustomerList
    }


    /**
     * 查询现货品种列表
     */
    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 ?: "",
                    enumdicname = it.enumdicname ?: ""
                )
            )
        }
        return newSpotVarietiesList
    }

    /**
     * 用来请求选择现货品种后的型号和品牌信息
     * @param wrstandardid String
     */
    fun queryWrStandardDetail(wrstandardid: String) {
        val params = mutableMapOf<String, String>().apply {
            put("userid", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("wrstandardid", wrstandardid)
        }

        MyApplication.getInstance()?.commodityManager?.queryWrStandardDetail(params) { isSuccess, respData, _ ->
            if (isSuccess) {
                wrStandardDataDetail.postValue(respData)
            }
        }
    }

    /**
     * 根据选择控件进行数据重新组装（型号）
     * @param data WrStandardDetail
     * @return ArrayList<SelectData>
     */
    fun selectWrStandardModel(data: WrStandardDetail): ArrayList<SelectData> {
        val wrstandardModel = arrayListOf<SelectData>()
        data.gtList.forEach {
            wrstandardModel.add(SelectData(id = it.modelid, value = it.modelname))
        }
        return wrstandardModel
    }

    /**
     * 根据选择控件进行数据重新组装（品牌）
     * @param data WrStandardDetail
     * @return ArrayList<SelectData>
     */
    fun selectWrStandardBrand(data: WrStandardDetail): ArrayList<SelectData> {
        val wrstandardBrand = arrayListOf<SelectData>()
        data.gtList.forEach {
            wrstandardBrand.add(SelectData(id = it.modelid, value = it.modelname))
        }
        return wrstandardBrand
    }


    /**
     * 合同操作申请
     * @param contractInfo SpotContractInfo 参数
     * @param OperateType String 操作类型 操作类型-1:保存草稿2:提交申请3:审核通过4:审核拒绝5:撤回6:正常完结7:异常终止
     * @param Remark String 备注
     * @param SpotContractID String  现货合同ID(602+Unix秒时间戳(10位)+xxxxxx)（修改时传入）
     */
    fun orderContract(
        contractInfo: SpotContractInfo = SpotContractInfo(),
        OperateType: String,
        Remark: String = "",
        SpotContractID: String = "",
        isSuccess: (isCompleted: Boolean) -> Unit
    ) {
        loadingDialogStatus.value = TaskUiModel.inFlight()
        GlobalScope.launch {
            MyApplication.getInstance()?.contractManager?.orderContract(contractInfo = contractInfo,OperateType = OperateType,Remark = Remark,SpotContractID = SpotContractID){isCompleted, err ->
                if (isCompleted){
                    loadingDialogStatus.postValue(TaskUiModel.success(msg = "请求成功"))
                    isSuccess(true)
                }else{
                    loadingDialogStatus.postValue(TaskUiModel.failed(InteractiveException(errorMessage = err?.message!!)))
                }
            }
        }
    }


}