package com.sonic.cow.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.cow.dao.VoiceChatRecordDao;
import com.sonic.cow.domain.entity.VoiceChatRecord;
import com.sonic.cow.enums.VoiceChatStatusEnum;
import com.sonic.cow.service.VoiceChatRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 语音聊天记录
 *
 * @author code
 */
@Slf4j
@Service
public class VoiceChatRecordServiceImpl extends ServiceImpl<VoiceChatRecordDao, VoiceChatRecord> implements VoiceChatRecordService {

    @Override
    public Long add(Long userId, Long aiId, String roomId, String taskId,String endpoint) {
        VoiceChatRecord voiceChatRecord = new VoiceChatRecord();
        voiceChatRecord.setUserId(userId);
        voiceChatRecord.setAiId(aiId);
        voiceChatRecord.setRoomId(roomId);
        voiceChatRecord.setTaskId(taskId);
        voiceChatRecord.setStatus(VoiceChatStatusEnum.CALLING.getCode());
        voiceChatRecord.setEndpoint(endpoint);
        voiceChatRecord.setCreateTime(LocalDateTime.now());
        voiceChatRecord.setEditTime(LocalDateTime.now());
        save(voiceChatRecord);
        return voiceChatRecord.getId();
    }

    @Override
    public void updateStatus(String roomId, String taskId, VoiceChatStatusEnum status) {
        update(Wrappers.<VoiceChatRecord>lambdaUpdate()
                .set(VoiceChatRecord::getStatus, status.getCode())
                .eq(VoiceChatRecord::getRoomId, roomId)
                .eq(VoiceChatRecord::getTaskId, taskId)
        );
    }

    @Override
    public void updateDuration(String roomId, String taskId, Long duration) {
        update(Wrappers.<VoiceChatRecord>lambdaUpdate()
                .set(VoiceChatRecord::getDuration, duration)
                .set(VoiceChatRecord::getEditTime, LocalDateTime.now())
                .set(VoiceChatRecord::getStatus, VoiceChatStatusEnum.STOP.getCode())
                .eq(VoiceChatRecord::getRoomId, roomId)
                .eq(VoiceChatRecord::getTaskId, taskId)
        );
    }

    @Override
    public VoiceChatRecord getByRoomIdAndTaskId(String roomId, String taskId) {
        return getOne(Wrappers.<VoiceChatRecord>lambdaQuery().eq(VoiceChatRecord::getRoomId, roomId).eq(VoiceChatRecord::getTaskId, taskId).last("limit 1"));
    }

    @Override
    public VoiceChatRecord getByTaskId(String taskId) {
        return getOne(Wrappers.<VoiceChatRecord>lambdaQuery().eq(VoiceChatRecord::getTaskId, taskId).last("limit 1"));
    }
}