package cn.muchinfo.rma.business.future

import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.FutureDetailsData
import cn.muchinfo.rma.global.data.GoodsInfoAndQuotes
import cn.muchinfo.rma.global.data.QuoteDayData
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsInfo
import cn.muchinfo.rma.global.data.futureOrders.FutureEntrustData
import cn.muchinfo.rma.global.data.futureOrders.FutureHoldData
import cn.muchinfo.rma.global.database.AppDatabase
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.autoWidget.toArrayList
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
import java.util.ArrayList

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

    /**
     * GET_ER_MCP_GOODS
     */
    fun queryGoodsList(callback: (isCompleted: Boolean, err: Error?) -> Unit) {
        // 查询最大goodsId
        var lastUpdateTime = "0"
        var params = mutableMapOf<String, String>()
        if (SPUtils.getInstance().getString(Constant.GOODS_UPDATE_TIME).isNotEmpty()){
            lastUpdateTime = SPUtils.getInstance().getString(Constant.GOODS_UPDATE_TIME)
        }
        params["lastUpdateTime"] = lastUpdateTime
        // 对接接口
        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 {
                if (it != null) {
                    data.goodscode == it.outgoodscode
                } else {
                    false
                }
            }
            goodsInfoAndQuotesList?.remove(goodsInfoAndQuotes)
            goodsInfoAndQuotes?.quoteDayData = data
            goodsInfoAndQuotesList?.add(goodsInfoAndQuotes)
        }
    }

    /**
     * 获取企业风管期货历史委托单信息
     * @param params Map<String, String> accountID/资金账户ID startDate/ 开始时间 - 闭区间，格式：yyyy-MM-dd endDate / 结束时间 - 闭区间，格式：yyyy-MM-dd
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<FutureDetailsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryErmcpHisEntrustDetails(
        responseBack: (isSuccess: Boolean, respData: List<FutureEntrustData>?, error: Error?) -> Unit
    ){
        val params = mutableMapOf<String, String>()
        params["accountID"] = SPUtils.getInstance().getLong(Constant.SELECT_ACCOUNT_ID).toString()
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryErmcpHisOrderDetails",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<FutureEntrustData>>>(){
                override fun onResponse(response: BaseResult<List<FutureEntrustData>>?, id: Int) {
                    GlobalDataCollection.instance?.futureHisEntrustData = response?.data as ArrayList<FutureEntrustData>?
                    responseBack(true, response?.data, null)
                }

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

            }
        )
    }


    /**
     * 获取企业风管期货历史成交单信息
     * @param params Map<String, String> accountID/资金账户ID startDate/ 开始时间 - 闭区间，格式：yyyy-MM-dd endDate / 结束时间 - 闭区间，格式：yyyy-MM-dd goodsID/商品ID  buyOrSell/买卖方向，0：买 1：卖
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<FutureDetailsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryErmcpHisTradeDetails(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: List<FutureDetailsData>?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryErmcpHisTradeDetails",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<FutureDetailsData>>>(){
                override fun onResponse(response: BaseResult<List<FutureDetailsData>>?, id: Int) {
                    responseBack(true, response?.data, null)
                }

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

            }
        )
    }


    /**
     * 获取企业风管期货委托单信息
     * @param params Map<String, String> accountID/资金账户ID
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<FutureDetailsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryErmcpEntrustDetails(responseBack: (isSuccess: Boolean, respData: List<FutureEntrustData>?, error: Error?) -> Unit
    ){
        val params = mutableMapOf<String, String>()
        params["accountID"] = SPUtils.getInstance().getLong(Constant.SELECT_ACCOUNT_ID).toString()
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryErmcpOrderDetails",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<FutureEntrustData>>>(){
                override fun onResponse(response: BaseResult<List<FutureEntrustData>>?, id: Int) {
                    GlobalDataCollection.instance?.futureEntrustData = response?.data as ArrayList<FutureEntrustData>?
                    responseBack(true, response?.data, null)
                }

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

            }
        )
    }


    /**
     *
     * 获取企业风管期货历史成交单信息
     * @param params Map<String, String> accountID/资金账户ID goodsID/商品ID buyOrSell/买卖方向，0：买 1：卖
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<FutureDetailsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryErmcpTradeDetails(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: List<FutureDetailsData>?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryErmcpTradeDetails",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<FutureDetailsData>>>(){
                override fun onResponse(response: BaseResult<List<FutureDetailsData>>?, id: Int) {
                    responseBack(true, response?.data, null)
                }

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

            }
        )
    }



    /**
     * 获取企业风管期货持仓头寸信息
     * @param params Map<String, String> accountID/资金账户ID marketID/所属市场ID
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<FutureDetailsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryErmcpTradePosition(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: List<FutureHoldData>?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryErmcpTradePosition",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<FutureHoldData>>>(){
                override fun onResponse(response: BaseResult<List<FutureHoldData>>?, id: Int) {
                    GlobalDataCollection.instance?.futureHoldData = response?.data?.toArrayList()
                    responseBack(true, response?.data, null)
                }

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

            }
        )
    }



}