package com.remax.visualnovel.repository.api

import com.remax.visualnovel.R
import com.remax.visualnovel.api.service.AIService
import com.remax.visualnovel.app.base.app.CommonApplicationProxy
import com.remax.visualnovel.entity.request.AIGenerate
import com.remax.visualnovel.entity.request.AIGenerateImage
import com.remax.visualnovel.entity.request.AIHeadImgRequest
import com.remax.visualnovel.entity.request.AIIDRequest
import com.remax.visualnovel.entity.request.AlbumCreate
import com.remax.visualnovel.entity.request.AlbumDTO
import com.remax.visualnovel.entity.request.CardRequest
import com.remax.visualnovel.entity.request.ChatAlbum
import com.remax.visualnovel.entity.request.ClassificationRequest
import com.remax.visualnovel.entity.request.PageQuery
import com.remax.visualnovel.entity.request.QueryAlbumDTO
import com.remax.visualnovel.entity.request.SimpleCountDTO
import com.remax.visualnovel.entity.response.Album
import com.remax.visualnovel.entity.response.Character
import com.remax.visualnovel.entity.response.base.ApiFailedResponse
import com.remax.visualnovel.entity.response.base.Response
import com.remax.visualnovel.event.model.OnAILiked
import com.remax.visualnovel.extension.toast
import com.remax.visualnovel.manager.login.LoginManager
import com.remax.visualnovel.repository.api.base.BaseRepository
import com.remax.visualnovel.ui.wallet.manager.WalletManager
import com.pengxr.modular.eventbus.generated.events.EventDefineOfUserAIEvents
import javax.inject.Inject

/**
 * Created by HJW on 2022/11/15
 */
class AIRepository @Inject constructor(private val aiService: AIService) : BaseRepository() {

    suspend fun cardBind(aiId: String) = executeHttp {
        aiService.cardBind(AIIDRequest(aiId))
    }

    suspend fun cardLiked() = executeHttp {
        aiService.cardLiked()
    }

    suspend fun reportCard(request: CardRequest) = executeHttp(false) {
        aiService.reportCard(request)
    }

    suspend fun getHomeCard(request: ClassificationRequest) = executeHttp {
        aiService.getHomeCard(request)
    }

    suspend fun getHomeCardDetail(aiId: String) = executeHttp {
        aiService.getHomeCardDetail(AIIDRequest(aiId))
    }

    suspend fun getClassificationList(request: ClassificationRequest) = executeHttp {
        aiService.getClassificationList(request)
    }

    suspend fun getHeartbeatRank() = executeHttp {
        aiService.getHeartbeatRank()
    }

    suspend fun getGiftRank() = executeHttp {
        aiService.getGiftRank()
    }

    suspend fun getChatRank() = executeHttp {
        aiService.getChatRank()
    }

    suspend fun getExploreInfo() = executeHttp {
        aiService.getExploreInfo()
    }


    suspend fun unlockSecret(dto: AIIDRequest): Response<Album> {
        return if (WalletManager.balance < 5000L) {
            WalletManager.showChargeDialog()
            ApiFailedResponse()
        } else {
            executeHttp {
                aiService.unlockSecret(dto)
            }
        }.transformResult({
            WalletManager.refreshWallet()
        })
    }

    suspend fun unlockAlbum(dto: ChatAlbum): Response<Album> {
        return if ((dto.unlockPrice ?: 0) > WalletManager.balance) {
            WalletManager.showChargeDialog()
            ApiFailedResponse()
        } else {
            executeHttp {
                aiService.unlockAlbum(dto)
            }
        }.transformResult({
            WalletManager.refreshWallet()
        })
    }

    suspend fun setAlbumUnlockPrice(dto: AlbumDTO) = executeHttp {
        aiService.setAlbumUnlockPrice(dto)
    }

    suspend fun setAILikeOrCancel(dto: AlbumDTO) = executeHttp {
        aiService.setAILikeOrCancel(dto)
    }.transformResult({
        EventDefineOfUserAIEvents.onAILikedChanged().post(OnAILiked(dto.aiId,dto.liked))
    })

    suspend fun deleteAICharacter(aiId: String) = executeHttp {
        aiService.deleteAICharacter(Character(aiId))
    }.transformResult({
        CommonApplicationProxy.application.toast(R.string.delete_succeed_toast)
        EventDefineOfUserAIEvents.onAICharacterChanges().post(aiId)
    })

    suspend fun setAlbumDefault(aiId: String, albumId: Long) = executeHttp {
        aiService.setAlbumDefault(AlbumDTO(aiId = aiId, albumId = albumId))
    }.transformResult({
        EventDefineOfUserAIEvents.onAIHomeImageChanges().post(aiId)
    })

    suspend fun editAIAvatar(request: AIHeadImgRequest) = executeHttp {
        aiService.editAIAvatar(request)
    }

    suspend fun createOrEditAICharacter(request: Character) = executeHttp {
        aiService.createOrEditAICharacter(request)
    }.transformResult({
        EventDefineOfUserAIEvents.onAICharacterChanges().post(it?.aiId)
    })

    suspend fun generateAICharacter(request: AIGenerate) = executeHttp {
        aiService.generateAICharacter(request)
    }

    suspend fun getAICharacter(aiId: String) = executeHttp {
        aiService.getAICharacter(Character(aiId = aiId))
    }

    suspend fun getAICharacterProfile(aiId: String) = executeHttp {
        aiService.getAICharacterProfile(Character(aiId = aiId))
    }

    suspend fun getAICharacterStat(aiId: String) = executeHttp {
        aiService.getAICharacterStat(Character(aiId = aiId))
    }

    suspend fun addAlbum(request: AlbumCreate) = executeHttp {
        aiService.addAlbum(request)
    }

    suspend fun getAlbumCreateCount() = executeHttp {
        aiService.getAlbumCreateCount()
    }

    suspend fun buyAlbumCreateCount(count: Int) = executeHttp {
        aiService.buyAlbumCreateCount(SimpleCountDTO(count))
    }.transformResult({
        WalletManager.refreshWallet()
    })

    suspend fun addChatBackground(request: AlbumCreate) = executeHttp {
        aiService.addChatBackground(request)
    }

    /**
     * 喜欢或取消喜欢相片
     */
    suspend fun setLikeOrDislike(albumId: Long, isLike: Boolean) = executeHttp {
        aiService.setLikeOrDislike(AlbumDTO(albumId, if (isLike) Album.CANCELED else Album.LIKED))
    }

    /**
     * 删除相片
     */
    suspend fun deleteAlbum(albumId: Long) = executeHttp {
        aiService.deleteAlbum(AlbumDTO(albumId, userId = LoginManager.user?.userId))
    }

    suspend fun getAlbumList(dto: QueryAlbumDTO) = executeHttp {
        aiService.getAlbumList(dto)
    }.transformResult({
        it?.datas?.forEach { item ->
            item.userId = dto.userId
            item.aiId = dto.aiId
        }
    })

    suspend fun getUserGiftList(aiId: String) = executeHttp {
        aiService.getUserGiftList(QueryAlbumDTO(aiId, null, PageQuery.Page(1).apply { this.ps = 100 }))
    }

    suspend fun generateImageBatch(request: AIGenerateImage) = executeHttp {
        aiService.generateImageBatch(request.apply {
            hl = this.aiId != null
        })
    }.transformResult({
        when(request.type){
            /**
             * 生成背景每次都要扣钱
             */
            AIGenerateImage.BACKGROUND -> WalletManager.refreshWallet()
        }
    })

    /**
     * AI一键生成-删除图片生成任务
     */
    suspend fun generateImageBatchDel(batchNo: String) = executeHttp {
        aiService.generateImageBatchDel(AIGenerateImage(batchNo = batchNo))
    }

    /**
     * AI一键生成-轮询查询图片生成结果
     */
    suspend fun generateImageBatchQuery(batchNo: String) = executeHttp {
        aiService.generateImageBatchQuery(AIGenerateImage(batchNo = batchNo))
    }

    /**
     * 获取相册 分页
     */
//    suspend fun getAlbumList(userId: Int, custId: String?, id: Int, imgOrder: Int) = executeHttp {
//        userService.getAlbumList(QueryAlbumDTO(userId, custId, id, imgOrder))
//    }
}