package cn.muchinfo.rma.view.base.procurement

import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.global.GlobalDataCollection

import cn.muchinfo.rma.global.ViewEnumUtils
import cn.muchinfo.rma.global.data.*
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.app.Constant
import com.blankj.utilcode.util.TimeUtils

import mtp.polymer.com.autowidget.utils.TaskUiModel
import java.util.*

class ProcurementViewModel : BaseViewModel() {

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

    /**
     * 待点价头部数据
     */
    val forSomePriceTitle: MutableLiveData<List<ColumnsData>> = MutableLiveData()

    /**
     * 履约结算头部数据
     */
    val settlementTitle: MutableLiveData<List<ColumnsData>> = MutableLiveData()

    /**
     * all头部数据
     */
    val allTitle: MutableLiveData<List<ColumnsData>> = MutableLiveData()

    /**
     * 合同详情业务管理列表点价数据
     */
    val somePriceList: MutableLiveData<List<BusinessData>> = MutableLiveData()

    /**
     * 合同详情业务管理列表结算数据
     */
    val settlementList: MutableLiveData<List<BusinessData>> = MutableLiveData()

    /**
     * 合同详情业务管理列表款项数据
     */
    val paymentList : MutableLiveData<List<FinancialManageData>> = MutableLiveData()

    /**
     * 合同详情业务管理列表发票数据
     */
    val invoiceList : MutableLiveData<List<FinancialManageData>> = MutableLiveData()

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


    /**
     * 查询采购列表头部数据
     * @param tableKey String
     */
    fun queryTitle(tableKey: String) {
        val params = mutableMapOf<String, String>().apply {
            put("tableKey", tableKey)
            put("tableType", "3")
        }
        MyApplication.getInstance()?.commonManager?.queryTableDefine(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                when (tableKey) {
                    Constant.table_mobile_purchase_pointprice -> {
                        val newlist = respData?.get(0)?.columns?.toArrayList()
                        newlist?.sortWith(Comparator { t1, t2 ->
                            t1.orderindex?.toInt()?.minus(t2.orderindex?.toInt() ?: 0) ?: 0
                        })
                        forSomePriceTitle.postValue(newlist)
                        queryContract("2","1")
                    }
                    Constant.table_mobile_purchase_settle -> {
                        val newlist = respData?.get(0)?.columns?.toArrayList()
                        newlist?.sortWith(Comparator { t1, t2 ->
                            t1.orderindex?.toInt()?.minus(t2.orderindex?.toInt() ?: 0) ?: 0
                        })
                        settlementTitle.postValue(newlist)
                        queryContract("3","1")
                    }
                    Constant.table_mobile_purchase_all -> {
                        val newlist = respData?.get(0)?.columns?.toArrayList()
                        newlist?.sortWith(Comparator { t1, t2 ->
                            t1.orderindex?.toInt()?.minus(t2.orderindex?.toInt() ?: 0) ?: 0
                        })
                        allTitle.postValue(newlist)
                        queryContract("1","1")
                    }
                }
            } else {

            }
        }
    }

    /**
     * 2待点价数据
     */
    val forSomePriceDataList: MutableLiveData<List<ContractData>> = MutableLiveData()

    /**
     * 3履约结算数据
     */
    val settlementDataList: MutableLiveData<List<ContractData>> = MutableLiveData()

    /**
     * 全部数据
     */
    val allDataList: MutableLiveData<List<ContractData>> = MutableLiveData()

    /**
     * 查询合同信息
     * @param type String 1 全部 2待点价 3履约结算
     * contracttype 合同类型 1-采购, -1-销售
     */
    fun queryContract(type: String,contracttype : String) {
        val params = mutableMapOf<String, String>().apply {
            put("userId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("contracttype", contracttype)
            put("querytype", type)
        }
        MyApplication.getInstance()?.commonManager?.queryContract(params = params) { isSuccess, respData, error ->
            if (isSuccess) {
                when (type) {
                    "1" -> {
                        allDataList.postValue(getAllRightData(respData ?: arrayListOf()))
                    }
                    "2" -> {
                        forSomePriceDataList.postValue(
                            getSomePriceRightData(
                                respData ?: arrayListOf()
                            )
                        )
                    }
                    "3" -> {
                        settlementDataList.postValue(
                            getSettlementRightData(
                                respData ?: arrayListOf()
                            )
                        )
                    }
                }
            }
        }
    }

    /**
     * 待点价组装右部数据
     * @param respData List<ContractData>
     * @return List<ContractData>
     */
    fun getSomePriceRightData(respData: List<ContractData>): List<ContractData> {
        val newList = arrayListOf<ContractData>()
        respData.forEach {
            val newRightData = arrayListOf<String>()
            newRightData.add(it.deliverygoodsname + "\n" + it.spotgoodsdesc)
            newRightData.add(it.goodsname + "\n" + it.pricemove)
            newRightData.add(it.qty+ it.enumdicname + "\n" + it.unpricedqty + it.enumdicname)
            newRightData.add(it.pricedqty+ it.enumdicname + "\n" + it.unsureqty+ it.enumdicname)
            newRightData.add(it.payamount + "\n" + it.unpayamount)
            newRightData.add(it.invoiceamount + "\n" + it.daikaiamount)
            newRightData.add(getTimeString(it))
            newRightData.add(it.convertfactor ?: "--")
            val newData = it.copy(rightData = newRightData)
            newList.add(newData)
        }
        return newList
    }

    /**
     * 履约结算组装右部数据
     * @param respData List<ContractData>
     * @return List<ContractData>
     */
    fun getSettlementRightData(respData: List<ContractData>): List<ContractData> {
        val newList = arrayListOf<ContractData>()
        respData.forEach {
            val newRightData = arrayListOf<String>()
            newRightData.add(it.deliverygoodsname + "\n" + it.spotgoodsdesc)
            newRightData.add(it.goodsname + "\n" + it.pricemove)
            newRightData.add(it.pricedqty + it.enumdicname + "\n" + it.unsureqty+ it.enumdicname)
            newRightData.add(it.payamount + "\n" + it.unpayamount)
            newRightData.add(it.invoiceamount + "\n" + it.daikaiamount)
            newRightData.add(getTimeString(it))
            newRightData.add(it.convertfactor ?: "--")
            newRightData.add(it.qty + "\n" + it.unpricedqty)
            val newData = it.copy(rightData = newRightData)
            newList.add(newData)
        }
        return newList
    }

    /**
     * 全部组装右部数据
     * @param respData List<ContractData>
     * @return List<ContractData>
     */
    fun getAllRightData(respData: List<ContractData>): List<ContractData> {
        val newList = arrayListOf<ContractData>()
        respData.forEach {
            val newRightData = arrayListOf<String>()
            newRightData.add(ViewEnumUtils.getContractStatus(it.contracctstatus ?: ""))
            newRightData.add(it.deliverygoodsname + "\n" + it.spotgoodsdesc)
            newRightData.add(it.goodsname + "\n" + it.pricemove)
            newRightData.add(
                it.convertfactor + "\n" + ViewEnumUtils.getContractStatus(
                    it.contracctstatus ?: ""
                )
            )
            newRightData.add(it.qty+ it.enumdicname + "\n" + it.unpricedqty+ it.enumdicname)
            newRightData.add(it.pricedqty+ it.enumdicname + "\n" + it.unsureqty+ it.enumdicname)
            newRightData.add(it.payamount + "\n" + it.unpayamount)
            newRightData.add(it.invoiceamount + "\n" + it.daikaiamount)
            newRightData.add(getTimeString(it))
            val newData = it.copy(rightData = newRightData)
            newList.add(newData)
        }
        return newList
    }

    fun getTimeString(data: ContractData): String {
        var dstartDate = "--"
        var denddate = "--"
        var startdate = "--"
        var enddate = "--"
        if (data.deliverystartdate.isNullOrEmpty().not()) {
            dstartDate = data.deliverystartdate?.substring(6, 10) ?: "--"
        }

        if (data.deliveryenddate.isNullOrEmpty().not()) {
            denddate = data.deliveryenddate?.substring(6, 10) ?: "--"
        }
        if (data.startdate.isNullOrEmpty().not()) {
            startdate = data.startdate?.substring(6, 10) ?: "--"
        }
        if (data.enddate.isNullOrEmpty().not()) {
            enddate = data.enddate?.substring(6, 10) ?: "--"
        }

        return "$dstartDate~$denddate\n$startdate~$enddate"
    }


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


    /**
     * 请求业务管理点价列表
     */
    fun queryBusinessDJ(relatedid : String) {
        val params = mutableMapOf<String, String>().apply {
            put("UserId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("relatedid", relatedid)
        }
        MyApplication.getInstance()?.businessManager?.queryBusinessDJ(params) { isSuccess, respData, _ ->
            if (isSuccess){
                respData?.toArrayList()?.sortWith(Comparator { t1, t2 ->
                    (TimeUtils.string2Millis(t2.applytime) - TimeUtils.string2Millis(t1.applytime)).toInt()
                })
                somePriceList.postValue(respData)
            }
        }
    }


    /**
     * 请求业务管理结算列表
     */
    fun queryBusinessJS(relatedid : String) {
        val params = mutableMapOf<String, String>().apply {
            put("UserId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("relatedid", relatedid)
        }

        MyApplication.getInstance()?.businessManager?.queryBusinessJSEx(params) { isSuccess, respData, _ ->
            if (isSuccess){
                respData?.toArrayList()?.sortWith(Comparator { t1, t2 ->
                    (TimeUtils.string2Millis(t2.applytime) - TimeUtils.string2Millis(t1.applytime)).toInt()
                })
                settlementList.postValue(respData)
            }
        }
    }


    /**
     * 款项列表请求
     */
    fun queryBusinessKx(relatedid : String){
        val params = mutableMapOf<String, String>().apply {
            put("UserId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("relatedid", relatedid)
        }

        MyApplication.getInstance()?.financialManager?.queryBusinessKx(params = params){isSuccess, respData, error ->
            if (isSuccess){
                paymentList.postValue(respData)
            }
        }
    }


    /**
     * 发票列表请求
     */
    fun queryBusinessFp(relatedid : String){
        val params = mutableMapOf<String, String>().apply {
            put("UserId", GlobalDataCollection.instance?.loginRsp?.userID.toString())
            put("relatedid", relatedid)
        }

        MyApplication.getInstance()?.financialManager?.queryBusinessFp(params = params){isSuccess, respData, error ->
            if (isSuccess){
                invoiceList.postValue(respData)
            }
        }
    }


    /**
     * 查询变更记录
     * @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)
            }
        }
    }


}