package com.bc_chat.bc_base.task

import com.bc_chat.bc_base.entity.ListModel
import com.bc_chat.bc_base.entity.UserInfo
import com.bc_chat.bc_base.http.Encryption
import com.bc_chat.bc_base.http.RetrofitHelper
import com.bc_chat.bc_base.utils.AppConfig
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 ChooseContactSelfDataSource : RxDataSource<UserInfo, ListModel<UserInfo>>() {

    override fun loadListFromNetWork(params: HashMap<String, Any?>): Flowable<ResultEntity<ListModel<UserInfo>>>? {
        return RetrofitHelper.api.getChooseFriendList(Encryption.encryption(params)).map {

            val resultEntity = ResultEntity<ListModel<UserInfo>>()
            val indexBarEntity = ListModel<UserInfo>()
            resultEntity.data = indexBarEntity
            resultEntity.error = it.error
            resultEntity.message = it.message
            addCurrentUser(it.data as MutableList<UserInfo>)
                .filter {
                    !it.userId.equals(Const.SYSTEM_NOTICE_ID)
                }.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)
                }
            return@map resultEntity
        }
    }

    private fun addCurrentUser(data: MutableList<UserInfo>): MutableList<UserInfo> {
        val userInfo = UserInfo()
        val user = AppConfig.instance.getUser()
        userInfo.userId = user.userId
        userInfo.nickname = user.nickname
        userInfo.photo = user.photo
        data.add(userInfo)
        return data
    }

    override fun hasMore(): Boolean {
        return false
    }
}
