package cn.muchinfo.rma.business.customer.adapter

import cn.muchinfo.rma.business.global.MessageHeadModel
import cn.muchinfo.rma.global.ErrorMessageUtils
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.netcore.packet.Packet50
import cn.muchinfo.rma.protobuf.funcode.FunCode
import cn.muchinfo.rma.protobuf.protoclasses.ManageServiceMI2
import java.io.ByteArrayOutputStream
import java.lang.Exception

/**
 * 客户资料相关装解箱
 */
object CustomerAdapter {

    /**
     * 客户信息审核报文装箱
     * @param auditflag Long 1审核通过2审核拒绝
     * @param userid Long 客户userid
     * @param audituserid Long 审核操作人userid
     * @param remark String 备注
     * @return Packet50
     */
    fun getCustomerDataReqInfo(
        auditflag : Long,
        userid : Long,
        audituserid : Long,
        remark : String = ""
    ) : Packet50{
        val builder = ManageServiceMI2.UserInfoCheckMangeReq.newBuilder()
        builder.auditflag = auditflag
        builder.userid = userid
        builder.audituserid = audituserid
        if (remark.isNotEmpty()){
            builder.remark = remark
        }

        val loginInfo = GlobalDataCollection.instance?.loginRsp
        // FIXME: - 250000000005
        builder.setHeader(
            MessageHeadModel.getHead(
                FunCode.UserInfoCheckMangeReq,
                loginInfo?.userID ?: 0,
                GlobalDataCollection.instance?.accountId ?: 0,
                0,
                18
            )
        )

        val arrayOutputStream = ByteArrayOutputStream();
        builder.build().writeTo(arrayOutputStream)
        return Packet50(FunCode.UserInfoCheckMangeReq, arrayOutputStream.toByteArray())
    }

    /**
     * 客户信息审核报文解析
     * @param packet50 Packet50
     * @return Triple<Boolean, Error?, ManageServiceMI2.?>
     */
    fun analysisCustomerDataRsq(packet50: Packet50): Triple<Boolean, Error?, ManageServiceMI2.UserInfoCheckMangeRsp?> {
        return try {
            val loginRsp = ManageServiceMI2.UserInfoCheckMangeRsp.parseFrom(packet50.content)
            if (loginRsp.retCode == 0) {
                // 操作成功
                Triple(true, null, loginRsp)
            } else {
                // 操作失败
                Triple(false, Error(ErrorMessageUtils.getErrorString(loginRsp.retCode)), null)
            }
        } catch (e: Exception) {
            // 操作失败
            Triple(false, Error("装箱失败"), null)
        }
    }

}