package com.ys.bdtp.adm.mvvm.vm.project

import com.ys.bdtp.adm.mvvm.model.nt.Response
import com.ys.bdtp.adm.mvvm.model.db.AdmDatabase
import com.ys.bdtp.adm.mvvm.model.db.entity.task.ProjectEntity
import com.ys.bdtp.adm.mvvm.model.db.entity.UserEntity
import com.ys.bdtp.adm.mvvm.model.db.entity.relation.UserWithProjects
import com.ys.bdtp.adm.mvvm.model.nt.Api
import com.ys.bdtp.adm.mvvm.model.nt.request
import com.ys.bdtp.adm.mvvm.model.vo.request.Account
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext


/**
 * ProjectRepository
 *
 * @author bai
 *
 * @param
 */
class ProjectRepository(private val api: Api, private val db: AdmDatabase) {
    /**
     * 获取账号信息
     */
    suspend fun getAccount(): Response<Account> {
        return withContext(Dispatchers.IO) {
            request {
                api.getAccount()
            }
        }
    }

    /**
     * 获取项目信息
     */
    suspend fun getProjects(): List<ProjectEntity> {
        return withContext(Dispatchers.IO) {
            db.projectDao().getProjects()
        }
    }

    /**
     * 设置当前账号信息
     */
    suspend fun setCurrentAccount(account: Account) {
        return withContext(Dispatchers.IO) {
            val user = UserEntity(
                password = "",
                state = 1,
                id = account.id,
                account = account.account,
                deptId = account.deptId,
                email = account.email,
                phone = account.phone,
                name = account.name,
            )
            val users = db.userDao().getUsers().onEach { u -> u.state = 0 }
            db.userDao().insUsers(users)
            db.userDao().insUser(user)
            account.projects.forEach { it.userId = user.id }
            db.projectDao().insProjects(account.projects)
        }
    }

    suspend fun getUserWithProjectsById(id: String): UserWithProjects {
        return withContext(Dispatchers.IO) {
            db.userDao().getUserWithProjectsById(id)
        }
    }

    /**
     * 获取当前登录的用户
     */
    suspend fun getCurrentUser(): UserEntity? {
        return withContext(Dispatchers.IO) {
            db.userDao().currentUser()
        }
    }

    fun getUser(): Flow<UserEntity?> {
        val flow = db.userDao().getUser()
        return flow
    }

    suspend fun logout() {
        withContext(Dispatchers.IO) {
            val user = db.userDao().currentUser()
            if (user != null) {
                user.state = 0
                db.userDao().updUser(user)
            }
        }
    }
}