package com.rdiot.yx485.room

import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.base.BaseViewModel
import com.rdiot.yx485.bean.CreatRoomBean
import com.rdiot.yx485.bean.DeteleRoomBean
import com.rdiot.yx485.bean.DeviceRoomListBean
import com.rdiot.yx485.bean.DeviceRoomListBean.RoomBean
import com.rdiot.yx485.bean.EditDeviceReply
import com.rdiot.yx485.bean.RoomDeviceDetailBean
import com.rdiot.yx485.bean.RoomDeviceDetailBean.RoomDeviceList
import com.rdiot.yx485.http.Url
import com.rdiot.yx485.http.entity.BaseReplyBean
import com.rdiot.yx485.util.LocalCache
import com.zcolin.frame.http.ZHttp
import com.zcolin.frame.http.ZReply
import com.zcolin.frame.http.response.ZResponse
import com.zcolin.frame.http.response.ZStringResponse
import com.zcolin.frame.util.GsonUtil
import okhttp3.Call
import okhttp3.Response

class RoomViewModel : BaseViewModel() {

    private var mRoomList = MutableLiveData<List<RoomBean>?>()
    val roomList: LiveData<List<RoomBean>?>
        get() = mRoomList

    /**
     * 设备房间
     */
    fun loadRoomList(homeId: String? = null) {
        val map: MutableMap<String?, String?> = HashMap<String?, String?>()
        map.put("q", "list")
        map.put("home_id", homeId ?: LocalCache.getDefaultHomeId())
        ZHttp.getWithHeader<DeviceRoomListBean?>(
            Url.ROOMS,
            getHeaders(),
            map,
            object : ZResponse<DeviceRoomListBean?>() {
                override fun onSuccess(response: Response?, resObj: DeviceRoomListBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            mRoomList.value = it.data
                            val list = it.data.map { room -> room.record_id }.toList()
                            LogUtils.d(Gson().toJson(list))

                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    /**
     * 创建房间
     */
    fun createRoom(homeId: String?, name: String?) {
        val room = CreatRoomBean()
        room.name = name
        room.home_id = homeId ?: LocalCache.getDefaultHomeId()

        ZHttp.postJsonWithHeader<BaseReplyBean?>(
            Url.ROOMCREATE,
            getHeaders(),
            room,
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            loadRoomList(homeId)
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    /**
     * 删除房间
     */
    fun deleteRoom(homeId: String?, id: String?) {
        val bean = DeteleRoomBean()
        bean.home_id = homeId ?: LocalCache.getDefaultHomeId()
        bean.record_ids = ArrayList<String?>()
        bean.record_ids.add(id)
        ZHttp.deteleJsonWithHeader<ZReply?>(
            Url.ROOMS,
            getHeaders(),
            GsonUtil.beanToString(bean),
            object : ZStringResponse() {
                override fun onError(code: Int, call: Call?, e: Exception?) {
                    mErrorMessage.value = e?.message
                }

                override fun onSuccess(response: Response?, resObj: String?) {
                    resObj?.let {
                        if (TextUtils.isEmpty(it) || !it.startsWith("{") || !it.endsWith("}")) {
                            return
                        }
                        val result = Gson().fromJson(it, BaseReplyBean::class.java)
                        if (result?.isSuccess == true) {
                            loadRoomList(homeId)
                            return
                        }

                        mErrorMessage.value = result?.message
                    }
                }
            })
    }

    fun updateRoomOrder(rooms: List<RoomBean>) {
        val orderList = rooms.map { room ->
            room.record_id
        }.toList()
        val params = HashMap<String, Any>()
        params["record_ids"] = orderList
        val json = Gson().toJson(params)
        LogUtils.d(json)
        ZHttp.putJsonWithHeader(
            Url.UPDATE_ROOM_ORDER,
            getHeaders(),
            json,
            object : ZResponse<BaseReplyBean>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            loadRoomList()
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    data class RoomOrder(
        val room_id: String,
        val sort: Int
    )

    private val _roomDeviceList = MutableLiveData<RoomDeviceList>()
    val roomDeviceList: LiveData<RoomDeviceList> = _roomDeviceList

    /**
     * 设备房间
     */
    fun loadDeviceList(roomId: String) {
        ZHttp.getWithHeader<RoomDeviceDetailBean?>(
            Url.ALLDEVICE + roomId + "/all_device",
            getHeaders(),
            object : ZResponse<RoomDeviceDetailBean?>() {
                override fun onSuccess(response: Response?, resObj: RoomDeviceDetailBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            _roomDeviceList.value = it.data
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }

    private val _updateState = MutableLiveData<Boolean>()
    val updateState: LiveData<Boolean> = _updateState

    fun upRoomInfo(id: String, replyBean: EditDeviceReply) {
        val url = Url.ROOM_UPDATE.replace("{id}", id)
        LogUtils.d(url)
        val json = Gson().toJson(replyBean)
        LogUtils.d(json)
        ZHttp.putJsonWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            json,
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        _updateState.value = it.isSuccess
                        if (!it.isSuccess) {
                            mErrorMessage.value = it.message
                        }
                    }
                }

                override fun onError(code: Int, error: String?) {
                    super.onError(code, error)
                    mErrorMessage.value = error
                }
            })
    }
}