package com.bc_chat.bc_base.entity.dao

import android.content.ContentValues
import android.net.Uri
import android.text.TextUtils
import com.bc_chat.bc_base.entity.User
import com.bc_chat.bc_base.entity.contact.Contacts
import com.bc_chat.bc_base.entity.dao.group.TGroup
import com.bc_chat.bc_base.entity.dao.group.TGroupMember
import com.bc_chat.bc_base.entity.dao.group.TMember
import com.bc_chat.bc_base.entity.group.Group
import com.bc_chat.bc_base.entity.group.MemberBean
import com.zhaohaoting.framework.utils.Logger
import io.rong.imkit.RongIM
import io.rong.imkit.model.GroupUserInfo
import io.rong.imlib.model.UserInfo
import org.litepal.tablemanager.Connector

/**
 * author：Created by zhaohaoting on 2019/3/6
 * email：526309416@qq.com
 * desc：
 */
class GroupMemberDao {

    companion object {
        val instance: GroupMemberDao by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            GroupMemberDao()
        }
    }

    /**
     * 缓存群信息
     */
    fun syncGroupInfo(groupList: List<Group>?) {
        if (groupList == null) return
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                beginTransaction()
                val clearStatement = compileStatement("Delete from ${TGroup::class.java.simpleName}")
                clearStatement.executeUpdateDelete()
                val insertStatement = compileStatement("insert into ${TGroup::class.java.simpleName} (groupId,group_name,photo,endTime,type)VALUES (?,?,?,?,?)")
                groupList.forEach {
                    RongIM.getInstance().refreshGroupInfoCache(io.rong.imlib.model.Group(it.groupId, it.group_name, Uri.parse(it.photo)))
                    insertStatement.bindString(1, it.groupId)
                    insertStatement.bindString(2, it.group_name)
                    insertStatement.bindString(3, it.photo)
                    insertStatement.bindString(4, if (it.endTime.isNullOrEmpty()) "0" else it.endTime)
                    insertStatement.bindString(5, if (it.type == null) "0" else it.type.toString())

                    insertStatement.executeInsert()
                }
                setTransactionSuccessful()
                endTransaction()
                close()
            }
        }
    }

    /**
     * 缓存群信息
     */
    fun syncGroupInfo(groupId: String, group: Group?) {
        if (group == null || TextUtils.isEmpty(groupId)) return
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                beginTransaction()
                val cursor = rawQuery("select groupId from ${TGroup::class.java.simpleName} where groupId = ?", arrayOf(groupId))
                val updateStatement = compileStatement("update ${TGroup::class.java.simpleName} set  group_name =?,photo=?,endTime=?,type=? where groupId = ?")
                val insertStatement = compileStatement("insert into ${TGroup::class.java.simpleName} (groupId,group_name,photo,endTime,type)VALUES (?,?,?,?,?)")
                if (cursor.count > 0) {
                    updateStatement.bindString(1, group.group_name)
                    updateStatement.bindString(2, group.photo)
                    updateStatement.bindString(3, if (group.endTime.isNullOrEmpty()) "0" else group.endTime)
                    updateStatement.bindString(4, if (group.type == null) "0" else group.type.toString())
                    updateStatement.bindString(5, groupId)
                    updateStatement.executeUpdateDelete()
                } else {
                    insertStatement.bindString(1, groupId)
                    insertStatement.bindString(2, group.group_name)
                    insertStatement.bindString(3, group.photo)
                    insertStatement.bindString(4, if (group.endTime.isNullOrEmpty()) "0" else group.endTime)
                    insertStatement.bindString(5, if (group.type == null) "0" else group.type.toString())
                    insertStatement.executeInsert()
                }
                cursor.close()
                setTransactionSuccessful()
                endTransaction()
                close()
            }
        }
    }

    /**
     * 缓存群信息
     */
    fun updateGroupName(groupId: String, groupName: String) {
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val contentValues = ContentValues()
                contentValues.put("group_name", groupName)
                update(TGroup::class.java.simpleName, contentValues, "groupId = ?", arrayOf(groupId))
                close()
            }
        }
    }

    /**
     * 缓存群信息
     */
    fun updateGroupHead(groupId: String, photo: String) {
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val contentValues = ContentValues()
                contentValues.put("photo", photo)
                update(TGroup::class.java.simpleName, contentValues, "groupId = ?", arrayOf(groupId))
                close()
            }
        }
    }

    /**
     * 缓存群用户列表
     */
    fun syncGroupMemberInfo(groupId: String, groupList: List<MemberBean>?) {
        if (groupList == null || TextUtils.isEmpty(groupId)) return
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                beginTransaction()
                val clearStatement1 = compileStatement("Delete from ${TGroupMember::class.java.simpleName} where groupId = $groupId")
                clearStatement1.executeUpdateDelete()
                val insertStatement = compileStatement("insert into ${TGroupMember::class.java.simpleName} (userId,groupId,role,groupUserName,groupUserPhoto) VALUES (?,?,?,?,?)")
                groupList.forEach {
                    insertStatement.bindString(1, it.userId)
                    insertStatement.bindString(2, groupId)
                    insertStatement.bindString(3, it.type.toString())
                    insertStatement.bindString(4, it.remark ?: it.nickname ?: "")
                    insertStatement.bindString(5, it.photo)
                    insertStatement.executeInsert()
                }

                val inertStatement = compileStatement("insert into ${TMember::class.java.simpleName} (userId,phone,photo,nickName,remarkName,type) VALUES (?,?,?,?,?,?)")
                val updateStatement = compileStatement("update ${TMember::class.java.simpleName} set  phone = ?,photo=?,nickName=?,remarkName=?,type=? where userId = ?")

                groupList.forEach {
                    RongIM.getInstance().refreshGroupUserInfoCache(GroupUserInfo(groupId, it.userId, it.remark
                            ?: it.nickname))
                    val cursor = rawQuery("select userId from ${TMember::class.java.simpleName} where userId = ?", arrayOf(it.userId))
                    if (cursor.count < 1) {
                        inertStatement.bindString(1, it.userId)
                        inertStatement.bindString(2, it.phone)
                        inertStatement.bindString(3, it.photo)
                        inertStatement.bindString(4, it.nickname)
                        inertStatement.bindString(5, it.remark ?: it.nickname ?: "")
                        inertStatement.bindString(5, if (it.type == null) "0" else it.type.toString())
                        inertStatement.executeInsert()
                    } else {
                        updateStatement.bindString(1, it.phone)
                        updateStatement.bindString(2, it.photo)
                        updateStatement.bindString(3, it.nickname)
                        updateStatement.bindString(4, it.remark ?: it.nickname ?: "")
                        updateStatement.bindString(5, if (it.type == null) "0" else it.type.toString())
                        updateStatement.bindString(6, it.userId)
                        updateStatement.executeUpdateDelete()
                    }
                    cursor.close()
                }
                setTransactionSuccessful()
                endTransaction()
                close()
            }
        }
    }

    /**
     * 缓存联系人
     */
    fun saveContactsInfo(contactList: List<Contacts>?) {
        if (contactList == null) return
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                beginTransaction()
                val inertStatement = compileStatement("insert into ${TMember::class.java.simpleName} (userId,photo,nickName,remarkName,endTime,type) VALUES (?,?,?,?,?,?)")
                val updateStatement = compileStatement("update ${TMember::class.java.simpleName} set  photo=?,nickName=?,remarkName=? ,endTime=?,type=? where userId = ?")
                contactList.forEach {
                    RongIM.getInstance().refreshUserInfoCache(UserInfo(it.userId, it.remark
                            ?: it.nickname, Uri.parse(it.photo)))
                    val cursor = rawQuery("select userId from ${TMember::class.java.simpleName} where userId = ?", arrayOf(it.userId))
                    if (cursor.count < 1) {
                        inertStatement.bindString(1, it.userId)
                        inertStatement.bindString(2, it.photo)
                        inertStatement.bindString(3, it.nickname)
                        inertStatement.bindString(4, it.remark ?: it.nickname ?: "")
                        inertStatement.bindString(5, if (it.endTime.isNullOrEmpty()) "0" else it.endTime)
                        inertStatement.bindString(6, if (it.type == null) "0" else it.type.toString())
                        inertStatement.executeInsert()
                    } else {
                        updateStatement.bindString(1, it.photo)
                        updateStatement.bindString(2, it.nickname)
                        updateStatement.bindString(3, it.remark ?: it.nickname ?: "")
                        updateStatement.bindString(4, if (it.endTime.isNullOrEmpty()) "0" else it.endTime)
                        updateStatement.bindString(5, if (it.type == null) "0" else it.type.toString())
                        updateStatement.bindString(6, it.userId)
                        updateStatement.executeUpdateDelete()
                    }
                    cursor.close()
                }
                setTransactionSuccessful()
                endTransaction()
                close()
            }
        }
    }

    /**
     * 缓存个人信息
     */
    fun saveMemberInfo(userId: String, user: User?) {
        if (user == null || TextUtils.isEmpty(userId)) return
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                beginTransaction()
                RongIM.getInstance().refreshUserInfoCache(UserInfo(userId, user.remark
                        ?: user.nickname, Uri.parse(user.photo)))
                val inertStatement = compileStatement("insert into ${TMember::class.java.simpleName} (userId,phone,photo,nickName,remarkName,endTime,type) VALUES (?,?,?,?,?,?,?)")
                val updateStatement = compileStatement("update ${TMember::class.java.simpleName} set  phone=?,photo=?,nickName=?,remarkName=?,endTime=? ,type = ? where userId = ?")
                val cursor = rawQuery("select userId from ${TMember::class.java.simpleName} where userId = ?", arrayOf(userId))
                if (cursor.count < 1) {
                    inertStatement.bindString(1, userId)
                    inertStatement.bindString(2, user.phone)
                    inertStatement.bindString(3, user.photo)
                    inertStatement.bindString(4, user.nickname)
                    inertStatement.bindString(5, user.remark ?: user.nickname)
                    inertStatement.bindString(6, if (user.endTime.isNullOrEmpty()) "0" else user.endTime)
                    inertStatement.bindString(7, if (user.type == null) "0" else user.type.toString())
                    inertStatement.executeInsert()
                } else {
                    updateStatement.bindString(1, user.phone)
                    updateStatement.bindString(2, user.photo)
                    updateStatement.bindString(3, user.nickname)
                    updateStatement.bindString(4, user.remark ?: user.nickname)
                    updateStatement.bindString(5, if (user.endTime.isNullOrEmpty()) "0" else user.endTime)
                    updateStatement.bindString(6, if (user.type == null) "0" else user.type.toString())
                    updateStatement.bindString(7, userId)
                    updateStatement.executeUpdateDelete()
                }
                cursor.close()
                setTransactionSuccessful()
                endTransaction()
                close()
            }
        }
    }

    /**
     * 缓存登录信息
     */
    fun saveUserInfo(saveUser: User?) {
        if (saveUser == null) return
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val cursor = rawQuery("select userId from ${User::class.java.simpleName} where userId = ?", arrayOf(saveUser.userId))
                val contentValues = ContentValues()
                contentValues.put("userId", saveUser.userId)
                contentValues.put("accessToken", saveUser.accessToken)
                contentValues.put("phone", saveUser.phone)
                contentValues.put("photo", saveUser.photo)
                contentValues.put("nickname", saveUser.nickname)
                contentValues.put("introduction", saveUser.introduction)
                contentValues.put("remark", saveUser.remark)
                contentValues.put("province", saveUser.province)
                contentValues.put("city", saveUser.city)
                contentValues.put("is_block", saveUser.is_block)
                contentValues.put("is_report", saveUser.is_report)
                contentValues.put("is_myFriend", saveUser.is_myFriend)
                contentValues.put("endTime", if (saveUser.endTime.isNullOrEmpty()) "0" else saveUser.endTime)
                contentValues.put("type", if (saveUser.type == null) "0" else saveUser.type.toString())
                if (cursor.count < 1) {
                    val insert = insert(User::class.java.simpleName, null, contentValues)
                    if (insert > 0) {
                        Logger.e("用户信息", "保存成功")
                    }
                } else {
                    val update = update(User::class.java.simpleName, contentValues, "userId = ?", arrayOf(saveUser.userId))
                    if (update > 0) {
                        Logger.e("用户信息", "保存成功")
                    }
                }
                cursor.close()
                close()
            }
//            saveUser.saveOrUpdateAsync("userId=${saveUser.userId}").listen { success -> Logger.e("用户信息", if (success) "保存成功" else "保存失败") }
        }
    }

    /**
     * 缓存登录信息
     */
    fun finUserById(userId: String): User? {
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val cursor = rawQuery("select userId,accessToken,phone,photo,nickname,introduction,remark,province,city,is_block,is_report,is_myFriend,endTime,type from ${User::class.java.simpleName} where userId = ?", arrayOf(userId))
                var user: User? = null
                while (cursor.moveToNext()) {
                    user = User(userId)
                    user.accessToken = cursor.getString(1)
                    user.phone = cursor.getString(2)
                    user.photo = cursor.getString(3)
                    user.nickname = cursor.getString(4)
                    user.introduction = cursor.getString(5)
                    user.remark = cursor.getString(6)
                    user.province = cursor.getString(7)
                    user.city = cursor.getString(8)
                    user.is_block = cursor.getInt(9)
                    user.is_report = cursor.getInt(10)
                    user.is_myFriend = cursor.getInt(11)
                    user.endTime = cursor.getString(12)
                    user.type = cursor.getInt(13)
                }
                cursor.close()
                close()
                return user
            }
            return null
//            return LitePal.where("userId=$userId").findLast(User::class.java)
        }
    }

    /**
     * 获取群友联系人
     */
    fun findMemberById(userId: String): TMember? {
        if (TextUtils.isEmpty(userId)) return null
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val cursor = rawQuery("select userId,phone,photo,nickName,remarkName,endTime,type from ${TMember::class.java.simpleName} where userId = ?", arrayOf(userId))
                var member: TMember? = null
                while (cursor.moveToNext()) {
                    member = TMember(userId)
                    member.userId = cursor.getString(0)
                    member.phone = cursor.getString(1)
                    member.photo = cursor.getString(2)
                    member.nickName = cursor.getString(3)
                    member.remarkName = cursor.getString(4)
                    member.endTime = cursor.getString(5)
                    member.type = cursor.getString(6)
                }
                cursor.close()
                close()
                return member
            }
        }
        return null
    }

    /**
     * 获取群和用户的关系
     */
    fun findGroupMemberById(groupId: String, userId: String): TGroupMember? {
        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(groupId)) return null
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val cursor = rawQuery("select groupId,userId,role,groupUserName,groupUserPhoto from ${TGroupMember::class.java.simpleName} where groupId=? and userId = ?", arrayOf(groupId, userId))
                var member: TGroupMember? = null
                while (cursor.moveToNext()) {
                    member = TGroupMember()
                    member.groupId = cursor.getString(0)
                    member.userId = cursor.getString(1)
                    member.role = cursor.getInt(2)
                    member.groupUserName = cursor.getString(3)
                    member.groupUserPhoto = cursor.getString(4)
                }
                cursor.close()
                close()
                return member
            }
        }
        return null
    }

    /**
     * 获取群信息
     */
    fun findGroupById(groupId: String): TGroup? {
        if (TextUtils.isEmpty(groupId)) return null
        synchronized(GroupMemberDao::class.java) {
            Connector.getDatabase().apply {
                val cursor = rawQuery("select groupId,group_name,photo,endTime,type from ${TGroup::class.java.simpleName} where groupId=? ", arrayOf(groupId))
                var member: TGroup? = null
                while (cursor.moveToNext()) {
                    member = TGroup()
                    member.groupId = cursor.getString(0)
                    member.group_name = cursor.getString(1)
                    member.photo = cursor.getString(2)
                    member.endTime = cursor.getString(3)
                    member.type = cursor.getString(4)
                }
                cursor.close()
                close()
                return member
            }
        }
        return null
    }
}
