package com.rc.httpcore.client.retrofit

import android.util.Log
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.client.LabClient
import com.rc.httpcore.exception.AICheckException
import com.rc.httpcore.exception.NetException
import com.rc.httpcore.vo.ByNameBean
import com.rc.httpcore.vo.CommonRowsResponse
import com.rc.httpcore.vo.GroupNameBean
import com.rc.httpcore.vo.request.*
import com.rc.httpcore.vo.response.*
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class LabRetrofit : LabClient {

    private val apiService by lazy {
        HttpClient.createRetrofitApi(ApiService::class.java)
    }

    private val signInCheckService by lazy {
        HttpClient.createRetrofitApi(ApiService::class.java, HttpConfig.SIGN_IN_CHECK_BASE_URL)
    }

    /**
     * 登录获取token
     */
    override fun authOneLogin(): Observable<Boolean> {
        val param = AccessTokenReq().apply {
            username = "onecUser"
            password = "admin123"
        }
        return apiService.authOneLogin(param)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                HttpClient.token = response.data?.access_token
                return@map !HttpClient.token.isNullOrEmpty()
            }
    }

    /**
     * 查询APK版本
     *
     * @param id 设备唯一编码
     */
    override fun apkVersion(id: String): Observable<ApkInfoResp> {
        return apiService.apkVersion(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 上传APK更新状态
     *
     * @param state 0:升级失败; 1:升级成功; 2:升级中
     */
    override fun onepcApkUpdate(id: String, state: String): Observable<Boolean> {
        return apiService.onepcApkUpdate(id, state)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map true
            }
    }

    /**
     * 实验室信息
     *
     * @param id 设备唯一编码
     */
    override fun laboratoryInfo(id: String): Observable<LaboratoryVo> {
        return apiService.laboratoryInfo(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 危险源信息
     *
     * @param param 实验室Id、分页信息
     */
    override fun hazardlist(param: HazardReq): Observable<List<LabHazardVo>> {
        return apiService.hazardlist(param.subId, param.pageNum, param.pageSize)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.rows
            }
    }

    /**
     * 签到验证（进入）
     *
     * @param eBoard 是否为电子信息牌
     * @param subId 实验室id
     * @param username 学生卡编号/人员id
     */
    override fun signInCheck(eBoard: Boolean, subId: String, username: String): Observable<SignInCheckResp> {
        val observable = if (eBoard) {
            apiService.signInXxpCheck(subId, username)
        } else {
            apiService.signInCheck(subId, username)
        }
        return observable.map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 签到提交-人脸验证
     */
    override fun signInFace(code: String, faceFeature: SignInReq?): Observable<String> {
        return apiService.signInFace(code, faceFeature)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 签到-安全准入检测三合一
     *
     * @param patrolSign 是否为巡查签到
     */
    override fun checkInAll(patrolSign: Boolean, param: CheckInAllReq): Observable<Boolean> {
        val fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), param.file)
        val filePart = MultipartBody.Part.createFormData("file", param.file.name, fileBody)

        val formMediaType = MediaType.parse("multipart/form-data")
        val bodyPartMap = mutableMapOf<String, RequestBody>()
        if (!param.id.isNullOrEmpty()) {
            bodyPartMap["id"] = RequestBody.create(formMediaType, param.id)
        }
        if (!param.subId.isNullOrEmpty()) {
            bodyPartMap["subId"] = RequestBody.create(formMediaType, param.subId)
        }

        val observable = if (patrolSign) {
            apiService.checkInXxpAll(bodyPartMap, filePart)
        } else {
            apiService.checkInAll(bodyPartMap, filePart)
        }
        return observable.map { response ->
                if (!response.isSuccess()) {
                    throw AICheckException(response.code, response.msg, response.data)
                }

                return@map true
            }
    }

    /**
     * 签到提交
     */
    override fun signIn(id: String): Observable<Boolean> {
        return apiService.signIn(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map true
            }
    }

    /**
     * 签到提交-有跳过安全准入检测时使用
     */
    override fun signInJump(id: String, code: String): Observable<Boolean> {
        return apiService.signInJump(id, code)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map true
            }
    }

    /**
     * 签到验证（离开）
     *
     * @param eBoard 是否为电子信息牌
     * @param subId 实验室id
     * @param username 学生卡编号/人员id
     */
    override fun signOutCheck(eBoard: Boolean, subId: String, username: String): Observable<SignInCheckResp> {
        val observable = if (eBoard) {
            apiService.signOutXXpCheck(subId, username)
        } else {
            apiService.signOutCheck(subId, username)
        }
        return observable.map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 离开提交
     */
    override fun signOut(code: String): Observable<Boolean> {
        return apiService.signOut(code)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map true
            }
    }

    /**
     * 获取实验室一体机可控制设备
     *
     * @param subId 实验室id
     */
    override fun controllerList(subId: String): Observable<List<LotDeviceVo>> {
        return apiService.controllerList(subId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 控制设备
     *
     * @param param 设备编号、命令
     */
    override fun sendControllerCMD(param: ControllerCMD): Observable<Boolean> {
        return apiService.sendControllerCMD(param.id, param.command)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map true
            }
    }

    /**
     * 实验室测点功能列表（首页-左侧看板）
     *
     * @param subId 实验室id
     */
    override fun functionList(subId: String): Observable<List<LabBulletinBoardVo>> {
        return apiService.functionList(subId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 实验室预警测点
     *
     * @param subId 实验室id
     */
    override fun warnList(subId: String): Observable<List<LabBulletinBoardVo>> {
        return apiService.warnList(subId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 人脸比对
     */
    override fun faceCompare(param: FaceCompareReq): Observable<Boolean> {
        return apiService.faceCompare(HttpConfig.BASE_PATH_FACE, param)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map true
            }
    }

    /**
     * 心跳
     *
     * @param num 设备唯一编码
     */
    override fun heartbeat(num: String): Observable<Boolean> {
        return apiService.heartbeat(num)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map true
            }
    }

    /**
     * 查询实验室安全制度列表
     *
     * @param type 1:学校制度 2:学院制度 3: 中心制度
     */
    override fun safeBookList(type: String): Observable<List<SafeBook>> {
        return apiService.safeBookList(type)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 获取实验室安全制度详细信息
     */
    override fun safeBookDetail(id: String): Observable<SafeBook> {
        return apiService.safeBookDetail(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 一体机查询危化品
     */
    override fun hazardBookList(): Observable<List<HazardBook>> {
        return apiService.hazardBookList()
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 获取危化品安全技术说明书详细信息
     */
    override fun hazardBookDetail(id: String): Observable<HazardBook> {
        return apiService.hazardBookDetail(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 查询实验室在线人员
     */
    override fun onlineUser(param: OnLineUserReq): Observable<CommonRowsResponse<LabPersonVo>> {
        return apiService.onlineUser(param)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response
            }
    }

    /**
     * 实验室安全整改信息
     */
    override fun checkMachineMsgList(subId: String): Observable<List<CheckMachineVo>> {
        return apiService.checkMachineMsgList(subId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.data
            }
    }

    /**
     * 实验室通知消息信息
     */
    override fun contentMachineMsgList(subId: String): Observable<List<ContentMachineVo>> {
        return apiService.contentMachineMsgList(subId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }

                return@map response.rows
            }
    }

    /**
     * 实验室文化图
     *
     * @param id 设备唯一编码
     */
    override fun bannerImages(id: String): Observable<List<BannerImageBean>> {
        return apiService.bannerImages(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 文字转语音
     */
    override fun textParseVideo(text: String): Observable<SpeakInfo> {
        return apiService.textParseVideo(HttpConfig.BASE_PATH_SPEAK, "50", "20", text)
            .map { response ->
                if ("0" != response.result) {
                    throw NetException("1000", "转换异常")
                }
                return@map response
            }
    }

    /**
     * 物联控制权限验证
     */
    override fun lotInCheck(subId: String, username: String): Observable<String> {
        return apiService.lotInCheck(subId, username)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询实验室配置
     */
    override fun queryLabConfig(deviceNum: String): Observable<LabConfig> {
        return apiService.queryLabConfig(deviceNum)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询首页头部信息
     */
    override fun homeTopInfo(labId: String): Observable<HomeTopResp> {
        return apiService.homeTopInfo(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询首页中部信息
     */
    override fun homeMiddleInfo(labId: String): Observable<HomeMiddleResp> {
        return apiService.homeMiddleInfo(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询首页右侧人员信息
     */
    override fun homeRightInfo(labId: String): Observable<HomeRightResp> {
        return apiService.homeRightInfo(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 实验室介绍
     */
    override fun labIntro(labId: String): Observable<String> {
        return apiService.labIntro(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询值班人员列表
     */
    override fun dutyUserList(labId: String, startTime: String): Observable<DutyPersonVo> {
        return apiService.dutyUserList(labId, startTime)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询实验人员列表
     */
    override fun signUserList(labId: String): Observable<List<LabPersonVo>> {
        return apiService.signUserList(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询准入人员列表
     */
    override fun securityUserList(labId: String, pageNumber: Int, pageSize: Int): Observable<List<LabPersonVo>> {
        return apiService.securityUserList(labId, pageNumber, pageSize)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 查询巡查人员列表
     */
    override fun inspectUserList(labId: String, startTime: String): Observable<DutyPersonVo> {
        return apiService.inspectUserList(labId, startTime)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 视频监控
     */
    override fun cameraBySubjectId(labId: String): Observable<List<MonitorVo>> {
        return apiService.cameraBySubjectId(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 获取准入人员的指纹信息列表
     */
    override fun getFingerList(labId: String): Observable<List<UserFingerVo>> {
        return apiService.getFingerList(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 根据用户查询指纹列表
     */
    override fun getFingerByUserId(labId: String, userId: String): Observable<List<UserFingerVo>> {
        return apiService.getFingerByUserId(labId, userId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 指纹录入
     */
    override fun addUserFinger(param: UserFingerVo): Observable<Boolean> {
        return apiService.addUserFinger(param)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map true
            }
    }

    /**
     * 删除指纹
     */
    override fun deleteFingerById(id: String): Observable<Boolean> {
        return apiService.deleteFingerById(id)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map true
            }
    }

    /**
     * 获取人像特征值
     */
    override fun faceFeature(file: File): Observable<String> {
        val fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file)
        val filePart = MultipartBody.Part.createFormData("file", file.name, fileBody)
        return apiService.faceFeature(filePart)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 人脸识别
     */
    override fun multiFaceDetection(param: AuthFaceReq): Observable<UserVo> {
        return apiService.multiFaceDetection(param)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 刷卡验证
     */
    override fun cardValidate(labId: String, cardNum: String): Observable<UserVo> {
        return apiService.cardValidate(labId, cardNum)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 密码验证
     */
    override fun pwdValidate(param: AuthPwdReq): Observable<UserVo> {
        return apiService.pwdValidate(param.num, param.labId, param.userId, param.pwd)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 校园卡是否能开启门禁
     */
    override fun getCardIsOpen(labId: String, cardNum: String): Observable<UserVo> {
        return apiService.getCardIsOpen(labId, cardNum)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 巡查签到
     */
    override fun signInWithPatrol(param: PatrolSignInReq): Observable<Boolean> {
        return apiService.signInWithPatrol(param)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map true
            }
    }

    /**
     * 巡查签退
     */
    override fun signOutWithPatrol(labId: String, userId: String): Observable<Boolean> {
        return apiService.signOutWithPatrol(labId, userId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map true
            }
    }

    /**
     * 巡查签退/准入签退判断
     *  true-巡查 false-准入
     */
    override fun isSignInType(labId: String, userId: String): Observable<Boolean> {
        return apiService.isSignInType(labId, userId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map "1" == response.data
            }
    }

    /**
     * 巡查签到前置校验
     */
    override fun signInCheckWithPatrol(labId: String, userId: String): Observable<Boolean> {
        return apiService.signInCheckWithPatrol(labId, userId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map true
            }
    }

    /**
     * 滚动消息列表
     */
    override fun newMsgGroup(labId: String): Observable<List<NoticeSummaryVo>> {
        return apiService.newMsgGroup(labId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 滚动消息列表
     */
    override fun getGroupNameList(subjectId: String): Observable<List<GroupNameBean>> {
        return apiService.getGroupNameList(subjectId)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    override fun getListByName(subjectId: String,gasName:String,remark:String?,flg:String?): Observable<List<ByNameBean>> {
//        Log.d("=======gggg======",remark)
//        Log.d("=======gggg======",subjectId)
//        Log.d("=======gggg======",gasName)
//        Log.d("=======gggg======",flg)
        return apiService.getListByName(subjectId,gasName,remark,flg)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.data
            }
    }

    /**
     * 通知消息列表
     */
    override fun newMsg(labId: String, pageNum: Int, pageSize: Int): Observable<List<NoticeDetailVo>> {
        return apiService.newMsg(labId, pageNum, pageSize)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.rows
            }
    }

    /**
     * 整改消息列表
     */
    override fun checkNewMsg(labId: String, pageNum: Int, pageSize: Int): Observable<List<NoticeDetailVo>> {
        return apiService.checkNewMsg(labId, pageNum, pageSize)
            .map { response ->
                if (!response.isSuccess()) {
                    throw NetException(response.code, response.msg)
                }
                return@map response.rows
            }
    }

}