package cn.muchinfo.rma.business.future

import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.GoodsInfoAndQuotes
import cn.muchinfo.rma.global.data.MiddleGoodsDetail
import cn.muchinfo.rma.global.data.QuoteDayData
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsInfo
import cn.muchinfo.rma.global.database.AppDatabase
import cn.muchinfo.rma.global.database.UserDatabase
import cn.muchinfo.rma.global.room.Builder
import cn.muchinfo.rma.netManage.base.ResponseCallback
import cn.muchinfo.rma.netManage.utils.MyOkHttpUtils
import cn.muchinfo.rma.view.base.app.BaseResult
import cn.muchinfo.rma.view.base.app.Constant
import cn.muchinfo.rma.view.base.app.ServiceFunApi
import com.blankj.utilcode.util.SPUtils
import okhttp3.Call
import java.lang.Exception

/**
 * 期货管理类
 */
class FutureManager {

    /**
     * GET_ER_MCP_GOODS
     */
    fun queryGoodsList(callback: (isCompleted: Boolean, err: Error?) -> Unit) {
        // 查询最大goodsId
        var goodsId = "0"
        var params = mutableMapOf<String, String>()
        if (SPUtils.getInstance().getString(Constant.GOODS_UPDATE_TIME).isNotEmpty()){
            goodsId = SPUtils.getInstance().getString(Constant.GOODS_UPDATE_TIME)
        }
//        params["lastUpdateTime"] = goodsId
        // 对接接口
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance()
                .getString(Constant.goCommonSearchUrl) + ServiceFunApi.GET_ER_MCP_GOODS,
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<GoodsInfo>>>() {
                override fun onResponse(response: BaseResult<List<GoodsInfo>>?, id: Int) {
                    // 存储直接入库，需要的时候，再查询，检查方法的运行时间，10ms可以接受
                    Builder.getDatabase<AppDatabase>().goodsInfoDao.insertAll(response?.data)
                    putGoodsInfoAndQuotesList()
                    callback(true, null)
                }

                override fun onError(call: Call?, e: Exception?, id: Int) {
                    callback(false, Error(e?.message))
                }
            }
        )
    }

    /**
     * 把数据库中的商品信息暂存本地数据中心
     */
    private fun putGoodsInfoAndQuotesList(){
        val goodsInfoList = Builder.getDatabase<AppDatabase>().goodsInfoDao.all
        val goodsInfoAndQuotesList = GlobalDataCollection.instance?.goodsInfoAndQuotesList
        goodsInfoList.forEach{
            goodsInfoAndQuotesList?.add(GoodsInfoAndQuotes(outgoodscode = it.outgoodscode,goodsInfo = it))
        }
    }

    /**
     * 获取商品盘面信息
     * @param params Map<String, String> goodsCodes 商品代码列表，格式：CU2102,CU2103,AL2107
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] MiddleGoodsDetail?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryQuoteDay(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: List<QuoteDayData>?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Quote/QueryQuoteDay",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<QuoteDayData>>>(){
                override fun onResponse(response: BaseResult<List<QuoteDayData>>?, id: Int) {
                    insertQuoteInGoodsInfoAndQuotesList(response?.data)
                    responseBack(true, response?.data, null)
                }

                override fun onError(call: Call?, e: Exception?, id: Int) {
                    responseBack(false, null, Error(e?.message))
                }

            }
        )
    }

    /**
     * 把查询到的盘面信息依据outgoodscode插入暂存的商品盘面信息内
     * @param quoteList List<QuoteDayData>
     */
    private fun insertQuoteInGoodsInfoAndQuotesList(quoteList : List<QuoteDayData>?){
        val goodsInfoAndQuotesList = GlobalDataCollection.instance?.goodsInfoAndQuotesList
        quoteList?.forEach {data ->
            val goodsInfoAndQuotes =  goodsInfoAndQuotesList?.find {
                data.goodscode == it.outgoodscode
            }
            val newInfoAndQuotes = goodsInfoAndQuotes
            goodsInfoAndQuotesList?.remove(goodsInfoAndQuotes)
            newInfoAndQuotes?.quoteDayData = data
            goodsInfoAndQuotesList?.add(newInfoAndQuotes)
        }
    }
}