package com.rdiot.yx485.home

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.CreateHomeBean
import com.rdiot.yx485.bean.DefHomeRoomBean
import com.rdiot.yx485.bean.HomeResultBean
import com.rdiot.yx485.bean.InviteBean
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.response.ZResponse
import okhttp3.Response

class HomeViewModel : BaseViewModel() {
    private var mHomeList = MutableLiveData<List<HomeResultBean.HomeInfo>>()
    val homeList: LiveData<List<HomeResultBean.HomeInfo>>
        get() = mHomeList

    /**
     * 获取数据
     */
    fun loadHomeList(isHomePage: Boolean = false) {
        val map: MutableMap<String?, String?> = HashMap<String?, String?>()
        map.put("q", "list")
        val isAdmin = if (isHomePage) "0" else "1"
        map.put("is_admin", isAdmin)
        ZHttp.getWithHeader<HomeResultBean?>(
            Url.HOMESLIST,
            getHeaders(),
            map,
            object : ZResponse<HomeResultBean?>() {
                override fun onSuccess(response: Response?, resObj: HomeResultBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            mHomeList.value = it.data
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

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

    private var mUpdateState = MutableLiveData<Boolean>()
    val updateState: LiveData<Boolean>
        get() = mUpdateState

    /**
     * 更新用户信息
     */
    fun updateHomeInfo(homeInfo: HomeResultBean.HomeInfo) {
        val url = Url.HOMEUPDATE.replace("{id}", homeInfo.record_id)
        ZHttp.putJsonWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            homeInfo,
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mUpdateState.value = it.isSuccess
                        if (it.isSuccess) {
                            loadHomeList()
                            return
                        }
                        mErrorMessage.value = it.message
                    }
                }

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

    private var mDeleteState = MutableLiveData<Boolean>()
    val deleteState: LiveData<Boolean>
        get() = mDeleteState

    /**
     * 删除家庭
     */
    fun deleteHome(id: String) {
        val url = Url.HOMEDELETE.replace("{id}", id)
        ZHttp.deteleWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            loadHomeList()
                        }
                    }
                }

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

    /**
     * 删除家庭
     */
    fun deleteHomeMember(homeId: String, id: String) {
        val url = String.format("%s?home_id=%s&user_id=%s", Url.FAMILYMEMBERLIST, homeId, id)
        ZHttp.deteleWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mDeleteState.value = it.isSuccess
                        if (!it.isSuccess) {
                            mErrorMessage.value = it.message
                        }
                    }
                }

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

    /**
     * 删除家庭
     */
    fun resetMemberRemark(memberId: String, remark: String) {
        val url = Url.FAMILY_MEMBER_REMARK.replace("{id}", memberId)
        val params = HashMap<String, String>()
        params["remark"] = remark
        ZHttp.putWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            Gson().toJson(params),
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mUpdateState.value = it.isSuccess
                        if (!it.isSuccess) {
                            mErrorMessage.value = it.message
                        }
                    }
                }

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

    private var mCityList = MutableLiveData<List<DefHomeRoomBean.DataBean.CityInfo>>()
    val cityList: LiveData<List<DefHomeRoomBean.DataBean.CityInfo>>
        get() = mCityList

    /**
     * cities列表
     */
    fun loadAllCities(parentId: String?) {
        val map: MutableMap<String?, String?> = java.util.HashMap<String?, String?>()
        map.put("q", "tree")
        map.put("pageSize", "99")
        map.put("current", "0")
        map.put("parent_id", parentId ?: "1")
        ZHttp.getWithHeader<DefHomeRoomBean?>(
            Url.HOMEDEFAULTS,
            getHeaders(),
            map,
            object : ZResponse<DefHomeRoomBean?>() {
                override fun onSuccess(response: Response?, resObj: DefHomeRoomBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            mCityList.value = it.data.list
                            LocalCache.saveCityList(it.data.list)
                            return
                        }
                        mErrorMessage.value = it.message
                    }
                }

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

    private var mCreateState = MutableLiveData<Boolean>()
    val createState: LiveData<Boolean>
        get() = mCreateState

    /**
     * 创建home
     */
    fun createHome(bean: CreateHomeBean) {
        ZHttp.postJsonWithHeader<BaseReplyBean?>(
            Url.HOMECREATE,
            getHeaders(),
            bean,
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mCreateState.value = it.isSuccess
                        if (it.isSuccess) {
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

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

    private var mDefaultRoomList = MutableLiveData<List<DefHomeRoomBean.DataBean.CityInfo>>()
    val defaultRoomList: LiveData<List<DefHomeRoomBean.DataBean.CityInfo>>
        get() = mDefaultRoomList

    /**
     * 房间列表
     */
    fun loadDefaultRoomList() {
        ZHttp.getWithHeader<DefHomeRoomBean?>(
            Url.FAMILYMEMBERLISTS,
            getHeaders(),
            object : ZResponse<DefHomeRoomBean?>() {
                override fun onSuccess(response: Response?, resObj: DefHomeRoomBean?) {
                    resObj?.let {
                        if (it.isSuccess) {
                            mDefaultRoomList.value = it.data.list
                            return
                        }

                        mErrorMessage.value = it.message
                    }
                }

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

    private var mInviteResult = MutableLiveData<Boolean>()
    val inviteResult: LiveData<Boolean>
        get() = mInviteResult

    /**
     * 邀请成员加入家庭
     * @param phone 手机号
     * @param homeId 家庭ID
     */
    fun inviteMember(phone: String, homeId: String) {
        val bean = InviteBean().apply {
            this.phone = phone
            this.home_id = homeId
        }

        ZHttp.postJsonWithHeader<BaseReplyBean>(
            Url.FAMILYMEMBER,
            getHeaders(),
            bean,
            object : ZResponse<BaseReplyBean>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mInviteResult.value = it.isSuccess
                        if (!it.isSuccess) {
                            mErrorMessage.value = it.message
                        }
                    }
                }

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

    fun initHomeAddress(province: String, city: String, district: String, address: String) {
        val home = LocalCache.getDefaultHome()
        home ?: return
        val url = Url.HOMEUPDATE.replace("{id}", home.id)
        val params = HashMap<String, String>()
        params["record_id"] = home.id
        params["name"] = home.name
        params["province"] = province
        params["city"] = city
        params["district"] = district
        params["address"] = address
        val json = Gson().toJson(params)
        ZHttp.putJsonWithHeader<BaseReplyBean?>(
            url,
            getHeaders(),
            json,
            object : ZResponse<BaseReplyBean?>() {
                override fun onSuccess(response: Response?, resObj: BaseReplyBean?) {
                    resObj?.let {
                        mUpdateState.value = it.isSuccess
                        if (it.isSuccess) {
                            loadHomeList()
                            return
                        }
                        mErrorMessage.value = it.message
                    }
                }

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