package com.bc_chat.contacts.dataSource

import com.bc_chat.bc_base.entity.ListModel
import com.bc_chat.bc_base.entity.contact.Contacts
import com.bc_chat.bc_base.entity.dao.GroupMemberDao
import com.bc_chat.bc_base.http.Encryption
import com.bc_chat.bc_base.http.RetrofitHelper
import com.bc_chat.bc_base.utils.Const
import com.zhaohaoting.framework.abs.datasource.RxDataSource
import com.zhaohaoting.framework.abs.entity.ResultEntity
import io.reactivex.Flowable
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/2/27
 * email：526309416@qq.com
 * desc：联系人列表
 */
class ContactDataSource : RxDataSource<Contacts, ListModel<Contacts>>() {

    override fun loadListFromNetWork(params: HashMap<String, Any?>): Flowable<ResultEntity<ListModel<Contacts>>>? {
        return RetrofitHelper.api.getFriendList(Encryption.encryption(params)).map {
            val resultEntity = ResultEntity<ListModel<Contacts>>()
            val indexBarEntity = ListModel<Contacts>()
            resultEntity.data = indexBarEntity
            resultEntity.error = it.error
            resultEntity.message = it.message
            val serviceUserList = it.data?.filter { it.userId.equals(Const.SYSTEM_NOTICE_ID) }
            val friendUserList = it.data?.filter { !it.userId.equals(Const.SYSTEM_NOTICE_ID) }
            serviceUserList?.let {
                indexBarEntity.list.addAll(it)
            }
            friendUserList?.let {
                var indexList: ArrayList<String> = arrayListOf()
                Collections.sort(it)
                //按照字母排序，中文转换为拼音后按字母排序
                var oldName: String? = null
                for (j in it.indices) {
                    val code = it[j]
                    if (code.firstLetter != oldName) {
                        code.isTop = true
                        indexList.add(code.firstLetter)
                    }
                    oldName = code.firstLetter
                }
                indexBarEntity.list.addAll(it)
                indexBarEntity.index.addAll(indexList)
            }

            GroupMemberDao.instance.saveContactsInfo(resultEntity.data.list)
            return@map resultEntity
        }
    }

    //    ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, Conversation.ConversationType.PRIVATE, Const.SYSTEM_NOTICE_ID, Const.SERVICE_NAME, null)
    override fun hasMore(): Boolean {
        return false
    }
}
