package cn.muchinfo.rma.business.commodity

import cn.muchinfo.rma.business.commodity.adapter.CommodityAdapter
import cn.muchinfo.rma.global.data.*
import cn.muchinfo.rma.netManage.base.ResponseCallback
import cn.muchinfo.rma.netManage.utils.MyOkHttpUtils
import cn.muchinfo.rma.netcore.packet.Packet50
import cn.muchinfo.rma.netcore.socket.Callback
import cn.muchinfo.rma.protobuf.funcode.FunCode
import cn.muchinfo.rma.protobuf.protoclasses.ManageServiceMI2
import cn.muchinfo.rma.view.MyApplication
import cn.muchinfo.rma.view.autoWidget.guard
import cn.muchinfo.rma.view.base.app.BaseResult
import cn.muchinfo.rma.view.base.app.Constant
import com.blankj.utilcode.util.SPUtils
import okhttp3.Call
import java.lang.Exception

/**
 * 商品信息管理类
 */
class CommodityManager {

    /**
     * 查询现货商品信息列表
     * @param params Map<String, String>
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<WrStandardData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryWrStandard(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: List<WrStandardData>?, error: Error?) -> Unit
    ) {
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance()
                .getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryWrStandard",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<WrStandardData>>>() {
                override fun onResponse(response: BaseResult<List<WrStandardData>>?, 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>
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] WrStandardDetail?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryWrStandardDetail(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: WrStandardDetail?, error: Error?) -> Unit
    ) {
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance()
                .getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryWrStandardDetail",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<WrStandardDetail>>() {
                override fun onResponse(response: BaseResult<WrStandardDetail>?, 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>
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] MiddleGoodsDetail?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryMiddleGoodsDetail(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: MiddleGoodsDetail?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryMiddleGoodsDetail",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<MiddleGoodsDetail>>(){
                override fun onResponse(response: BaseResult<MiddleGoodsDetail>?, 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>
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<GGConvertConfigData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryGGConvertConfig(
        params: Map<String, String> = mapOf(),
        responseBack: (isSuccess: Boolean, respData: List<GGConvertConfigData>?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl)  + "/Ermcp/QueryGGConvertConfig",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<GGConvertConfigData>>>(){
                override fun onResponse(response: BaseResult<List<GGConvertConfigData>>?, 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>
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<AvaildGoodsGroupData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryAvalidGoods(
        params: Map<String, String> ,
        responseBack: (isSuccess: Boolean, respData: List<AvaildGoodsGroupData>?, error: Error?) -> Unit
    ){
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance().getString(Constant.goCommonSearchUrl)  + "/Ermcp/QueryAvaildGoodsGroup",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<AvaildGoodsGroupData>>>(){
                override fun onResponse(response: BaseResult<List<AvaildGoodsGroupData>>?, 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>  status 状态 0-停用 1-正常
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<MiddleGoodsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryMiddleGoods(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: List<MiddleGoodsData>?, error: Error?) -> Unit
    ) {
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance()
                .getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryMiddleGoods",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<List<MiddleGoodsData>>>() {
                override fun onResponse(response: BaseResult<List<MiddleGoodsData>>?, 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> middlegoodsid 套保品种id
     * @param responseBack Function3<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] List<MiddleGoodsData>?, [@kotlin.ParameterName] Error?, Unit>
     */
    fun queryMiddleGoodsDetails(
        params: Map<String, String>,
        responseBack: (isSuccess: Boolean, respData: MiddleGoodsDetails?, error: Error?) -> Unit
    ) {
        MyOkHttpUtils().query(
            URL = SPUtils.getInstance()
                .getString(Constant.goCommonSearchUrl) + "/Ermcp/QueryMiddleGoodsDetail",
            params = params,
            type = "1",
            callback = object : ResponseCallback<BaseResult<MiddleGoodsDetails>>() {
                override fun onResponse(response: BaseResult<MiddleGoodsDetails>?, id: Int) {
                    responseBack(true, response?.data, null)
                }

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

            }
        )
    }

    /**
     * 现货品种申请请求
     * @param deliverygoodscode String 交割商品代码(新增时有值)
     * @param deliverygoodsname String 交割商品名称(新增时有值)
     * @param wrstandardid Long 现货商品ID(修改时有值)
     * @param unitid Long 单位ID
     * @param type Int 类型 1 新增 2 修改
     * @param remark String 备注
     * @param spotgoodsmodels List<SpotGoodsModelEx> SpotGoodsModelEx 现货商品型号数据
     * @param spotgoodsbrands List<SpotGoodsBrandEx> SpotGoodsBrandEx 现货商品品牌数据
     * @param wrsconvertdetails List<WRSConvertDetailEx> WRSConvertDetailEx 现货商品折算配置明细数据
     */
    fun requestGoodsApply(
        deliverygoodscode: String = "",
        deliverygoodsname: String = "",
        wrstandardid: Long = 0,
        unitid: Long = 0,
        type: Int = 0,
        remark: String = "",
        spotgoodsmodels: List<ManageServiceMI2.SpotGoodsModelEx> = arrayListOf(),
        spotgoodsbrands: List<ManageServiceMI2.SpotGoodsBrandEx> = arrayListOf(),
        wrsconvertdetails: List<ManageServiceMI2.WRSConvertDetailEx> = arrayListOf(),
        callback: (isCompleted: Boolean, err: Error?) -> Unit
    ) {
        val tradeSocketManager = MyApplication.getInstance()?.tradeSocketManager.guard {
            callback(false, Error("交易链路未初始化"))
            return
        }

        val reqPacket = CommodityAdapter.getGoodsApplyReqInfo(
            deliverygoodscode,
            deliverygoodsname,
            wrstandardid,
            unitid,
            type,
            remark,
            spotgoodsmodels,
            spotgoodsbrands,
            wrsconvertdetails
        )

        tradeSocketManager.send(
            reqPacket,
            FunCode.DeliveryGoodsApplyRsp,
            object : Callback<Packet50> {
                override fun onSuccess(rsp: Packet50?) {
                    val rst = CommodityAdapter.analysisGoodsApplyRsq(rsp!!)
                    callback(rst.first, rst.second)
                }

                override fun onFail(err: Error?) {
                    // 发送数据失败
                    callback(false, err)
                }

            }
        )
    }

    /**
     * 现货品种停用请求
     * @param wrstandardid Long现货商品ID
     * @param isvalid Int 0:无效 1:有效
     * @param callback Function2<[@kotlin.ParameterName] Boolean, [@kotlin.ParameterName] Error?, Unit>
     */
    fun requestGoodsCancelReq(
        wrstandardid: Long = 0,
        isvalid: Int = 0,
        callback: (isCompleted: Boolean, err: Error?) -> Unit
    ) {
        val tradeSocketManager = MyApplication.getInstance()?.tradeSocketManager.guard {
            callback(false, Error("交易链路未初始化"))
            return
        }

        val reqPacket = CommodityAdapter.getGoodsCancelReqInfo(wrstandardid, isvalid)

        tradeSocketManager.send(
            reqPacket,
            FunCode.DeliveryGoodsCancelRsp,
            object : Callback<Packet50> {
                override fun onSuccess(rsp: Packet50?) {
                    val rst = CommodityAdapter.analysisGoodsCancelRsq(rsp!!)
                    callback(rst.first, rst.second)
                }

                override fun onFail(err: Error?) {
                    // 发送数据失败
                    callback(false, err)
                }

            }
        )
    }

    /**
     * 套保品种新增请求
     * @param middlegoodsname String 套保品种名称
     * @param middlegoodscode String 套保品种代码
     * @param goodsunitid Int 单位ID
     * @param relatedgoodsid Long 关联交易商品ID
     * @param evaluateratio Double 估价系数
     * @param qtydecimalplace Int 数量小数位
     * @param creatorid Long 创建人
     * @param modifierid Long 修改人
     * @param relatedgoodstype Int 关联商品类型 - 1:期货合约 2:现货品种
     * @param needhedgeratio Double 套保比率
     * @param areauserid Long 机构用户ID
     * @param goodsgroupid Long 关联期货品种ID
     * @param remark String 备注
     */
    fun requestErmsMiddelGoodsReq(
        middlegoodsname: String = "",
        middlegoodscode: String = "",
        goodsunitid: Int = 0,
        relatedgoodsid: Long = 0,
        evaluateratio: Double = 0.0,
        qtydecimalplace: Int = 0,
        creatorid: Long = 0,
        modifierid: Long = 0,
        relatedgoodstype: Int = 0,
        needhedgeratio: Double = 0.0,
        areauserid: Long = 0,
        goodsgroupid: Long = 0,
        remark: String = "",
        callback: (isCompleted: Boolean, err: Error?) -> Unit
    ) {
        val tradeSocketManager = MyApplication.getInstance()?.tradeSocketManager.guard {
            callback(false, Error("交易链路未初始化"))
            return
        }

        val reqPacket = CommodityAdapter.getErmsMiddelGoodsReqInfo(
            middlegoodsname,
            middlegoodscode,
            goodsunitid,
            relatedgoodsid,
            evaluateratio,
            qtydecimalplace,
            creatorid,
            modifierid,
            relatedgoodstype,
            needhedgeratio,
            areauserid,
            goodsgroupid,
            remark
        )

        tradeSocketManager.send(
            reqPacket,
            FunCode.ErmsMiddelGoodsRsp,
            object : Callback<Packet50> {
                override fun onSuccess(rsp: Packet50?) {
                    val rst = CommodityAdapter.analysisErmsMiddelGoodsRsq(rsp!!)
                    callback(rst.first, rst.second)
                }

                override fun onFail(err: Error?) {
                    // 发送数据失败
                    callback(false, err)
                }

            }
        )
    }

    /**
     * 套保品种修改请求
     * @param middlegoodsid Long 套保品种ID
     * @param goodsunitid Int 单位ID
     * @param relatedgoodsid Long 关联交易商品ID
     * @param evaluateratio Double 估价系数
     * @param qtydecimalplace Int 数量小数位
     * @param modifierid Long 修改人
     * @param relatedgoodstype Int 关联商品类型 - 1:期货合约 2:现货品种
     * @param needhedgeratio Double 套保比率
     * @param areauserid Long 机构用户ID
     * @param goodsgroupid Long 关联期货品种ID
     * @param remark String 备注
     * @return Packet50
     */
    fun requestErmsMiddelGoodsEditReq(
        middlegoodsid: Long = 0,
        goodsunitid: Int = 0,
        relatedgoodsid: Long = 0,
        evaluateratio: Double = 0.0,
        qtydecimalplace: Int = 0,
        modifierid: Long = 0,
        relatedgoodstype: Int = 0,
        needhedgeratio: Double = 0.0,
        areauserid: Long = 0,
        goodsgroupid: Long = 0,
        remark: String = "",
        callback: (isCompleted: Boolean, err: Error?) -> Unit
    ) {
        val tradeSocketManager = MyApplication.getInstance()?.tradeSocketManager.guard {
            callback(false, Error("交易链路未初始化"))
            return
        }

        val reqPacket = CommodityAdapter.getErmsMiddelGoodsEditReqinfo(
            middlegoodsid,
            goodsunitid,
            relatedgoodsid,
            evaluateratio,
            qtydecimalplace,
            modifierid,
            relatedgoodstype,
            needhedgeratio,
            areauserid,
            goodsgroupid,
            remark
        )

        tradeSocketManager.send(
            reqPacket,
            FunCode.ErmsMiddelGoodsEditRsp,
            object : Callback<Packet50> {
                override fun onSuccess(rsp: Packet50?) {
                    val rst = CommodityAdapter.analysisErmsMiddelGoodsEditRsq(rsp!!)
                    callback(rst.first, rst.second)
                }

                override fun onFail(err: Error?) {
                    // 发送数据失败
                    callback(false, err)
                }

            }
        )
    }

    /**
     * 套保品种停用请求
     * @param middlegoodsid Long
     * @param isvalid Int
     * @param modifierid Long
     */
    fun requestErmsMiddelGoodsStopReq(
        middlegoodsid: Long = 0,
        isvalid: Int = 0,
        modifierid: Long = 0,
        callback: (isCompleted: Boolean, err: Error?) -> Unit
    ) {
        val tradeSocketManager = MyApplication.getInstance()?.tradeSocketManager.guard {
            callback(false, Error("交易链路未初始化"))
            return
        }

        val reqPacket = CommodityAdapter.getErmsMiddelGoodsStopReqInfo(middlegoodsid, isvalid, modifierid)

        tradeSocketManager.send(
            reqPacket,
            FunCode.ErmsMiddelGoodsStopRsp,
            object : Callback<Packet50> {
                override fun onSuccess(rsp: Packet50?) {
                    val rst = CommodityAdapter.analysisErmsMiddelGoodsStopRsq(rsp!!)
                    callback(rst.first, rst.second)
                }

                override fun onFail(err: Error?) {
                    // 发送数据失败
                    callback(false, err)
                }

            }
        )
    }

}